import sys
sys.version
'3.10.6 | packaged by conda-forge | (main, Aug 22 2022, 20:41:22) [Clang 13.0.1 ]'
import sys
sys.version
'3.10.6 | packaged by conda-forge | (main, Aug 22 2022, 20:41:22) [Clang 13.0.1 ]'
Construct a simple list:
= [1, 2, 3, 4, 5, 6, 7, 8, 9] a
Or using range()
:
= list(range(1, 10))
a a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Get squares of all even numbers in a:
= [x**2 for x in a if x%2 == 0]
b b
[4, 16, 36, 64]
Get the squares and cubes of all odd numbers in a:
= [[x**2, x**3] for x in a if x%2 == 1]
c c
[[1, 1], [9, 27], [25, 125], [49, 343], [81, 729]]
map()
= list(range(1, 10))
a a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Triple each element of a:
= list(map(lambda x: x * 3, a))
b b
[3, 6, 9, 12, 15, 18, 21, 24, 27]
Get the square of all even numbers and the cube of all odd numbers in a:
= list(map(lambda x: x**2 if x % 2 == 0 else x**3, a))
c c
[1, 4, 27, 16, 125, 36, 343, 64, 729]
filter()
Keep all even numbers in a:
= list(filter(lambda x: x%2 == 0, a))
even even
[2, 4, 6, 8]