first line of code:
for i in list: print(i)
second line of code:
print(i for i in list)
what would I use each of them for?
Advertisement
Answer
You can see for yourself what the difference is.
The first one iterates over range
and then prints integers.
>>> for i in range(4): ... print(i) ... 0 1 2 3
The second one is a generator expression.
>>> print(i for i in range(4)) <generator object <genexpr> at 0x10b6c20f0>
How iteration works in the generator. Python generators are a simple way of creating iterators.
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
>>> g=(i for i in range(4)) >>> print(g) <generator object <genexpr> at 0x100f015d0> >>> print(next(g)) 0 >>> >>> print(next(g)) 1 >>> print(next(g)) 2 >>> print(next(g)) 3 >>> print(next(g)) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> g=(i for i in range(4)) >>> for i in g: ... print(i) ... 0 1 2 3 >>> for i in g: ... print(i) ... >>> >>>
In python3, you can use tuple unpacking to print the generator. If that’s what you were going for.
>>> print(*(i for i in range(4))) 0 1 2 3