l = []
for i in range(10):
if i % 2 == 0:
l.append(i)
print(l)
The same thing is as follows in list comprehension notation
l = [i for i in range(10) if i % 2 ==0]
print(l)
output
[0, 2, 4, 6, 8]
w = ['Monday', 'Tuesday','Friday']
f = ['banana', 'apple', 'orange']
d= {}
for x, y in zip(w,f):
d[x]=y
print(d)
The same thing is as follows in the dictionary comprehension
w = ['Monday', 'Tuesday','Friday']
f = ['banana', 'apple', 'orange']
d = {x:y for x,y in zip(w,f)}
print(d)
output
{'Monday': 'banana', 'Tuesday': 'apple', 'Friday': 'orange'}
s = set()
for i in range(10):
if i % 2 == 0:
s.add(i)
print(s)
The same thing is as follows in the set comprehension notation
s = {i for i in range(10) if i % 2 == 0}
print(s)
output
{0, 2, 4, 6, 8}
def g():
for i in range(10):
if i % 2 == 0:
yield i
g = g()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
The same thing happens in the generator formula as follows.
g = (i for i in range(10) if i % 2 == 0)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
output
0
2
4
6
In addition, the official document says "generator notation", not "generator comprehension". https://docs.python.org/ja/3/reference/expressions.html#generator-expressions
A generator expression is a compact generator notation with parentheses: The generator expression gives a new generator object. This syntax is similar to the comprehension, but is enclosed in parentheses instead of square brackets or curly braces.
Recommended Posts