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