Similar ways to use generators in Python 3 -


i'm trying understand use of yield/generators in python. know, if given list of numbers (ex.: [1, 2, 3, 4, 5, 6, 7, 8, 9]) 2 following statements equivalent. if not, what's difference?

x = (n n in numbers) return x   n in numbers:     yield n 

as far know almost equivalent specified in pep 289:

g = (x**2 x in range(10)) print g.next() 

is equivalent to:

def __gen(exp):     x in exp:         yield x**2 g = __gen(iter(range(10))) print g.next() 

however it's almost equivalent, difference in case when iter(numbers) evaluated:

>>> def f1(l): ...     x = (n n in l) ...     return x ...  >>> def f2(l): ...     n in l: ...         yield n ...           >>> a1 = f1(1) typeerror: 'int' object not iterable  >>> a2 = f2(2)  # works >>> next(a2)    # fails after calling "next" typeerror: 'int' object not iterable 

f1 try iter(l) while f2 iter(l) after calling next on it.

to equivalent need pass iter(numbers) function uses yield.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -