first line of code:
JavaScript
x
3
1
for i in list:
2
print(i)
3
second line of code:
JavaScript
1
2
1
print(i for i in list)
2
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.
JavaScript
1
8
1
>>> for i in range(4):
2
print(i)
3
4
0
5
1
6
2
7
3
8
The second one is a generator expression.
JavaScript
1
3
1
>>> print(i for i in range(4))
2
<generator object <genexpr> at 0x10b6c20f0>
3
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).
JavaScript
1
32
32
1
>>> g=(i for i in range(4))
2
>>> print(g)
3
<generator object <genexpr> at 0x100f015d0>
4
>>> print(next(g))
5
0
6
>>>
7
>>> print(next(g))
8
1
9
>>> print(next(g))
10
2
11
>>> print(next(g))
12
3
13
>>> print(next(g))
14
Traceback (most recent call last):
15
File "<stdin>", line 1, in <module>
16
StopIteration
17
18
19
>>> g=(i for i in range(4))
20
>>> for i in g:
21
print(i)
22
23
0
24
1
25
2
26
3
27
>>> for i in g:
28
print(i)
29
30
>>>
31
>>>
32
In python3, you can use tuple unpacking to print the generator. If that’s what you were going for.
JavaScript
1
3
1
>>> print(*(i for i in range(4)))
2
0 1 2 3
3