Note: List comprehension

List comprehension

I will use it insanely, so make a note. For example, when you want to create a sequence of n ^ 2

python3


>>> l = [i**2 for i in range(6)]
>>> l 
[0, 1, 4, 9, 16, 25]

This way, f (x) for x in <iterator>] will return a list of f (x).

with if

If you write like this, you can narrow down to only the elements that meet the conditions

python3


>>> l = [i**2 for i in range(6) if i%2 == 0] //i only if i is even**Returns 2
>>> l 
[0, 4, 16]

with if else

If you want to change the value depending on whether the condition is met, use if else to make it look like this

python3


>>> l = [i**2 if i%2 == 0 else 'odd' for i in range(6)]
>>> l 
[0, 'odd', 4, 'odd', 16, 'odd']

Nest

Can be nested

python3


>>> l = [(i, j) for i in range(3) for j in ['a','b','c']]
>>> l
[(0, 'a'),
 (0, 'b'),
 (0, 'c'),
 (1, 'a'),
 (1, 'b'),
 (1, 'c'),
 (2, 'a'),
 (2, 'b'),
 (2, 'c')]

Recommended Posts

Note: List comprehension
List comprehension
List comprehension
Python> Comprehension / Comprehension> List comprehension
Python Exercise 2 --List Comprehension
FizzBuzz in list comprehension
Python list comprehension speed
Not just list comprehension
Quicksort 2 | Easy list comprehension
Note
Note
Judgment of if by list comprehension
Note: List of customized special names
Django note 4
Python basic operation 1st: List comprehension notation
Python comprehension
pyenv note
Comprehension notation
linked list
Python comprehension
Set comprehension
Python comprehension (list and generator expressions) [additional]
Note: Python
Join list
Python note
Django Note 1
direnv note
Django note 3
Django note 2
Comprehension notation
[Note] RepresenterError
[Python] List Comprehension Various ways to create a list
A note on customizing the dict list class
Note that Python list comprehensions are always confusing