DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on

Generator comprehension in Python

Buy Me a Coffee

*Memo:

  • My post explains a list comprehension.
  • My post explains a set comprehension.
  • My post explains a frozenset comprehension.
  • My post explains a dictionary comprehension.
  • My post explains a generator comprehension.
  • My post explains a generator (1).

A comprehension is the concise expression to create an iterable and there are a list, tuple, set, frozenset, dictionary(dict) and generator comprehension:

<Generator comprehension>:

*Memo:

  • Basically, a generator comprehension needs () but it can be passed to a function without ().

1D generator:

v = (x**2 for x in [0, 1, 2, 3, 4, 5, 6, 7])

print(v)
# <generator object <genexpr> at 0x0000024511AE4EE0>

for x in v:
    print(x)
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
Enter fullscreen mode Exit fullscreen mode

The below is without a generator comprehension:

def func(s):
    for x in s:
        yield x**2

sample = [0, 1, 2, 3, 4, 5, 6, 7]

v = func(sample)

for x in v:
    print(x)
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
Enter fullscreen mode Exit fullscreen mode
print(x**2 for x in range(8)) # With`()`
# <generator object <genexpr> at 0x000001C1CBA341E0>
Enter fullscreen mode Exit fullscreen mode
v = x**2 for x in range(8) # Without `()`
# SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

2D generator:

sample = [[0, 1, 2, 3], [4, 5, 6, 7]]

v = ((y**2 for y in x) for x in sample)

for x in v:
    for y in x:
        print(y)
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
Enter fullscreen mode Exit fullscreen mode

The below is without a generator comprehension:

def func(s):
    for x in s:
        def func(x):
            for y in x:
                yield y**2
        yield func(x)

sample = [[0, 1, 2, 3], [4, 5, 6, 7]]

v = func(sample)

for x in v:
    for y in x:
        print(y)
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
Enter fullscreen mode Exit fullscreen mode

3D generator:

sample = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]

v = (((z**2 for z in y) for y in x) for x in sample)

for x in v:
    for y in x:
        for z in y:
            print(z)
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
Enter fullscreen mode Exit fullscreen mode

The below is without a generator comprehension:

def func(s):
    for x in s:
        def func(x):
            for y in x:
                def func(y):
                    for z in y:
                       yield z**2
                yield func(y)
        yield func(x)

sample = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]

v = func(sample)

for x in v:
    for y in x:
        for z in y:
            print(z)
# 0
# 1
# 4
# 9
# 16
# 25
# 36
# 49
Enter fullscreen mode Exit fullscreen mode

Top comments (0)