DEV Community

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

Posted on

Comprehension in Python (3)

Buy Me a Coffee

*Memo:

  • My post explains a list and tuple comprehension.
  • My post explains a set and dictionary(dict) comprehension.
  • My post explains a generator.

<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]) 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)) # No `()` # <generator object <genexpr> at 0x000001C1CBA341E0> 
Enter fullscreen mode Exit fullscreen mode
v = x**2 for x in range(8) # No `()` # 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)