*Memos:
- My post explains a dictionary(dict) comprehension and generator comprehension.
A comprehension is the concise way to create an iterable. There are a list comprehension, tuple comprehension, set comprehension, dictionary(dict) comprehension and generator comprehension. *A comprehension is an expression.
<List Comprehension>
1D list:
v = [x**2 for x in range(6)]
print(v) # [0, 1, 4, 9, 16, 25]
*The below is without a list comprehension.
v = []
for x in range(6):
v.append(x**2)
print(v) # [0, 1, 4, 9, 16, 25]
2D list:
sample = [[0, 1, 2], [3, 4, 5]]
v = [[y**2 for y in x] for x in sample]
print(v) # [[0, 1, 4], [9, 16, 25]]
*The below is without a list comprehension.
sample = [[0, 1, 2], [3, 4, 5]]
v = []
for i, x in enumerate(sample):
v.append([])
for y in x:
v[i].append(y**2)
print(v) # [[0, 1, 4], [9, 16, 25]]
<Tuple Comprehension>
*tuple() is used for a tuple comprehension because ()
is already used for a generator comprehension.
1D tuple:
v = tuple(x**2 for x in range(6))
print(v) # (0, 1, 4, 9, 16, 25)
*The below is without a tuple comprehension.
v = []
for x in range(6):
v.append(x**2)
v = tuple(v)
print(v)
# (0, 1, 4, 9, 16, 25)
2D tuple:
sample = [[0, 1, 2], [3, 4, 5]]
v = tuple(tuple(y**2 for y in x) for x in sample)
print(v) # ((0, 1, 4), (9, 16, 25))
*The below is without a tuple comprehension.
sample = [[0, 1, 2], [3, 4, 5]]
v = []
for i, x in enumerate(sample):
v.append([])
for y in x:
v[i].append(y**2)
v[i] = tuple(v[i])
v = tuple(v)
print(v) # [[0, 1, 4], [9, 16, 25]]
# ((0, 1, 4), (9, 16, 25))
<Set Comprehension>
1D set:
v = {x**2 for x in range(6)}
print(v) # {0, 1, 4, 9, 16, 25}
*The below is without a set comprehension.
v = set()
for x in range(6):
v.add(x**2)
print(v) # {0, 1, 4, 9, 16, 25}
2D set:
sample = [[0, 1, 2], [3, 4, 5]]
v = {tuple(y**2 for y in x) for x in sample}
print(v) # {(9, 16, 25), (0, 1, 4)}
*The below is without a set comprehension.
sample = [[0, 1, 2], [3, 4, 5]]
v = set()
for x in sample:
def func(x):
for y in x:
yield y**2
v.add(tuple(func(x)))
print(v) # {(9, 16, 25), (0, 1, 4)}