Generator comprehension notation Tuple comprehension notation

1


def g():
    for i in range(10):
        yield i

g = g()
print(next(g))
print(next(g))
print(next(g))

Execution result of 1


0
1
2

If you write this in a comprehension

Generator comprehension


g = (i for i in range(10))

for j in range(3):
    print(next(g))

Execution result of generator comprehension


0
1
2

Since it is surrounded by (), at first glance, It looks like a tuple. The tuple inclusion notation is as follows.

Tuple comprehension


t = tuple(i for i in range(10))
print(t)

Tuple inclusion notation execution result


(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Generator comprehension 2


g = (i for i in range(10))

for j in g:
    print(j)

Execution result of generator comprehension 2


0
1
2
3
4
5
6
7
8
9

Generator comprehension 3


g = (i for i in range(10) if i % 3 == 0)

for j in g:
    print(j)

Execution result of generator comprehension 3


0
3
6
9

Recommended Posts

Generator comprehension notation Tuple comprehension notation
Comprehension notation
Comprehension notation
generator
Generator
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
Python basic operation 1st: List comprehension notation
Python comprehension (list and generator expressions) [additional]