Answer the question
In order to leave comments, you need to log in
2 examples: list generator and yield - the difference is not visible. Incorrect examples?
1. List generator:
gen_list = (x*x for x in range(3))
for i in gen_list:
print(i)
0
1
4
def gen_list():
lis = range(3)
for i in lis:
yield i*i
my_list = gen_list()
for i in my_gen:
print(i)
0
1
4
Answer the question
In order to leave comments, you need to log in
In addition to Pavel Denisov 's answer , I'll throw in the following option:
def forever(lst):
while True:
for item in lst:
yield item
def str_gen(lst):
for item in lst:
yield str(item)
','.join(str_get(lst))
In this case, the list comprehension is essentially a special case of yield.
yield allows multiple entry and exit from a function, this allows you to do different things, such as streaming data or "coroutines" for asynchronous applications.
that's right, generator functions differ in that they are more flexible. Generator expressions of the form(x**2 for x in range(5))
are just a simplified notation of a generator function for use in simple cases (not to be confused with list generators: [x**2 for x in range(5)]
. The only difference is in brackets, but the meaning is completely different, because generator expressions produce values on the go, the list generator creates the entire list in advance, and already then returns its values as an iterable).
Here is an example of a generator through a function
>>> def g():
... while True:
... yield 'a'
... yield 'b'
... yield 'c'
...
>>> list(zip(g(), range(10)))
[('a', 0), ('b', 1), ('c', 2), ('a', 3), ('b', 4), ('c', 5), ('a', 6), ('b', 7), ('c', 8), ('a', 9)]
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question