import sys
sys.version'3.13.3 (main, Apr 8 2025, 13:54:08) [Clang 16.0.0 (clang-1600.0.26.6)]'
import sys
sys.version'3.13.3 (main, Apr 8 2025, 13:54:08) [Clang 16.0.0 (clang-1600.0.26.6)]'
Construct a simple list:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]Or using range():
a = list(range(1, 10))
a[1, 2, 3, 4, 5, 6, 7, 8, 9]
Get squares of all even numbers in a:
b = [x**2 for x in a if x%2 == 0]
b[4, 16, 36, 64]
Get the squares and cubes of all odd numbers in a:
c = [[x**2, x**3] for x in a if x%2 == 1]
c[[1, 1], [9, 27], [25, 125], [49, 343], [81, 729]]
map()a = list(range(1, 10))
a[1, 2, 3, 4, 5, 6, 7, 8, 9]
Triple each element of a:
b = list(map(lambda x: x * 3, a))
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:
c = list(map(lambda x: x**2 if x % 2 == 0 else x**3, a))
c[1, 4, 27, 16, 125, 36, 343, 64, 729]
filter()Keep all even numbers in a:
even = list(filter(lambda x: x%2 == 0, a))
even[2, 4, 6, 8]