[PYTHON] Comprehension notation

List comprehension

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]

Dictionary comprehension

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'}

Set comprehension

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}

Generator type

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

Comprehension notation
Comprehension notation
Generator comprehension notation Tuple comprehension notation
List comprehension
Python comprehension
Set comprehension
Format notation
List comprehension
Python basic operation 1st: List comprehension notation
About python comprehension
filter vs comprehension
Folded tensor-like notation
[Introduction to Udemy Python3 + Application] 60. List comprehension notation
[Introduction to Udemy Python3 + Application] 62. Set comprehension notation
Python> Comprehension / Comprehension> List comprehension
Dictionary comprehensive notation
Note: List comprehension
Visualize N-ary notation
Let's do various things using Python's list comprehension notation