Python base level generator and list of questions

my_nums =(i*i for i in [1,2,3,4,5])
for k in (my_nums):
    print(k)
GG = list(my_nums)

print(GG)

He prints:

1
4
9
16
25
[]

Process finished with exit code 0

I do not understand why the value is []empty (should it be [1,4,9,16,25])? Also, for-loopconvert generator values ​​to list?

+4
source share
6 answers

The following is an understanding of the generator :

my_nums =(i*i for i in [1,2,3,4,5])

for k in (my_nums):
    print(k)

So, first you loop on it and print the values, the generator prints each value that it can generate. The for loop works by calling my_nums.next()and assigning the resulting value k, which is then printed. The iteration of the for loop stops when an exception occurs StopIteration.

GG = list(my_nums) for, , .

, , list, :

my_nums =(i*i for i in [1,2,3,4,5])
GG = list(my_nums) # no for loop for printing it already

, , , - , , .

+4

, !

my_nums = (i*i for i in [1,2,3,4,5])
for k in my_nums:
    print(k)

my_nums = (i*i for i in [1,2,3,4,5])
print(list(my_nums))
+1

, . , for k in (my_nums): print(k), .

:

my_nums =(i*i for i in [1,2,3,4,5])
a = list(my_nums)
b = list(my_nums)
print(a)
// [1,4,9,16,25]
print(b)
// []
0

, ,

for k in (my_nums): # you already made my_nums generate till the end here
    print(k)

. , , .

0

, :

my_nums = (item for item in [1, 2, 3, 4, 5, 6, 7])

- - :

def generator(iterable):
    for item in iterable:
        yield item

my_nums = generator([1, 2, 3, 4, 5, 6, 7])

forloop :

while True:
    try:
        item = next(my_nums)
    except StopIteration:
        break
    else:
        print(item)

gg = list(iterable) - :

gg = []
for item in my_nums:
    gg.append(item)

, . , StopIteration .

:

>>> my_nums = (i for i in [1, 2])
>>> list(my_nums)
[1, 2]
>>> list(my_nums)
[]
>>> next(my_nums)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

, list(my_nums), ? , . , StopIteration, .

0

- , . , " ".

my_nums =(i*i for i in [1,2,3,4,5])
for k in (my_nums):
    print(k)

:

1
4
9
16
25

, , () []. , for k in my_nums , : 1, 4 25 .

, StopIteration traceback.

.

0

All Articles