List comprehension

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

List comprehension
List comprehension
Python> Comprehension / Comprehension> List comprehension
Note: List comprehension
Python Exercise 2 --List Comprehension
FizzBuzz in list comprehension
Python list comprehension speed
Quicksort 2 | Easy list comprehension
linked list
Judgment of if by list comprehension
Set comprehension
Join list
[Python] list
Comprehension notation
Python basic operation 1st: List comprehension notation
Python comprehension (list and generator expressions) [additional]
[Python] List Comprehension Various ways to create a list
Linux command list
About python comprehension
filter vs comprehension
Python basics: list
Color code list
List type, tuple type 2
[Introduction to Udemy Python3 + Application] 60. List comprehension notation
list and sum
List type, tuple type
list and numpy
List AWS ami
Python list manipulation
List reverse operation
Let's do various things using Python's list comprehension notation
list comprehension because operator.methodcaller cannot be used in python 2.5
Python3 comprehension (List, dictionary) that I have seen somewhere