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)
.
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]
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']
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