1
t = (1, 2, 3, 4, 5)
l = []
for i in t:
l.append(i)
print(l)
Execution result of 1
[1, 2, 3, 4, 5]
If you write this in list comprehension
1 in list comprehension
t = (1, 2, 3, 4, 5)
l = [i for i in t]
print(l)
Execution result of 1 in list comprehension notation
[1, 2, 3, 4, 5]
Consider the case where only the number whose remainder after dividing by 3 is 0 is included in the list.
2
t = (1, 2, 3, 4, 5, 6)
l = []
for i in t:
if i % 3 == 0:
l.append(i)
print(l)
Execution result of 2
[3, 6]
If you write this in list comprehension
2 in list comprehension
t = (1, 2, 3, 4, 5, 6)
l = [i for i in t if i % 3 == 0]
print(l)
Execution result of 2 in list comprehension notation
[3, 6]
There are two tuples, If you want to list the number of operations
3
t = (1, 2, 3)
t2 = (4, 5, 6, 7, 8, 9)
l = []
for i in t:
for j in t2:
l.append(i * j)
print(l)
Execution result of 3
[4, 5, 6, 7, 8, 9, 8, 10, 12, 14, 16, 18, 12, 15, 18, 21, 24, 27]
If you write this in list comprehension
3 in list comprehension
t = (1, 2, 3)
t2 = (4, 5, 6, 7, 8, 9)
l = [i * j for i in t for j in t2]
print(l)
Execution result of 3 in list comprehension notation
[4, 5, 6, 7, 8, 9, 8, 10, 12, 14, 16, 18, 12, 15, 18, 21, 24, 27]
Just because you can write in list comprehension You can include two or three for loops, The longer the code, the harder it is to read and should be avoided.
It is preferable to set the above "2 in list comprehension" to the order.
Recommended Posts