*Memo:
- My post explains a tuple 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 list (1).
A comprehension is the concise expression to create an iterable and there are a list, tuple, set, frozenset, dictionary(dict) and generator comprehension:
<List comprehension>:
1D list:
sample = [0, 1, 2, 3, 4, 5, 6, 7]
v = [x**2 for x in sample]
print(v)
# [0, 1, 4, 9, 16, 25, 36, 49]
The below is without a list comprehension:
sample = [0, 1, 2, 3, 4, 5, 6, 7]
v = []
for x in sample:
v.append(x**2)
print(v)
# [0, 1, 4, 9, 16, 25, 36, 49]
2D list:
sample = [[0, 1, 2, 3], [4, 5, 6, 7]]
v = [[y**2 for y in x] for x in sample]
print(v)
# [[0, 1, 4, 9], [16, 25, 36, 49]]
The below is without a list comprehension:
sample = [[0, 1, 2, 3], [4, 5, 6, 7]]
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, 36, 49]]
3D list:
sample = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
v = [[[z**2 for z in y] for y in x] for x in sample]
print(v)
# [[[0, 1], [4, 9]], [[16, 25], [36, 49]]]
The below is without a list comprehension:
sample = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
v = []
for i, x in enumerate(sample):
v.append([])
for j, y in enumerate(x):
v[i].append([])
for z in y:
v[i][j].append(z**2)
print(v)
# [[[0, 1], [4, 9]], [[16, 25], [36, 49]]]
Top comments (0)