1point = (1, 2, 3)
2point(0:2) # (1, 2)
3x, y, z = point
4if 10 in point:
5 ...
6
7# Swapping variables
8x = 10
9y = 11
10x, y = y, x
11
1def increment(number, by=1):
2 return number + by
3
4# Keyword arguments
5increment(2, by=1)
6
7# Variable number of arguments
8def multiply(*numbers):
9 for number in numbers:
10 print number
11
12
13multiply(1, 2, 3, 4)
14
15# Variable number of keyword arguments
16def save_user(**user):
17 ...
18
19
20save_user(id=1, name="Mosh")
21
1point = {"x": 1, "y": 2}
2point = dict(x=1, y=2)
3point["z"] = 3
4if "a" in point:
5 ...
6point.get("a", 0) # 0
7del point["x"]
8for key, value in point.items():
9 ...
10
11# Dictionary comprehensions
12values = {x: x * 2 for x in range(5)}
13
1if x == 1:
2 print(“a”)
3elif x == 2:
4 print(“b”)
5else:
6 print(“c”)
7
8# Ternary operator
9x = “a” if n > 1 else “b”
10
11# Chaining comparison operators
12if 18 <= age < 65:
13
1values = (x * 2 for x in range(10000))
2len(values) # Error
3for x in values:
4
1# Creating lists
2letters = ["a", "b", "c"]
3matrix = [[0, 1], [1, 2]]
4zeros = [0] * 5
5combined = zeros + letters
6numbers = list(range(20))
7
8# Accessing items
9letters = ["a", "b", "c", "d"]
10letters[0] # "a"
11letters[-1] # "d"
12
13# Slicing lists
14letters[0:3] # "a", "b", "c"
15letters[:3] # "a", "b", "c"
16letters[0:] # "a", "b", "c", "d"
17letters[:] # "a", "b", "c", "d"
18letters[::2] # "a", "c"
19letters[::-1] # "d", "c", "b", "a"
20
21# Unpacking
22first, second, *other = letters
23
24# Looping over lists
25for letter in letters:
26 ...
27
28for index, letter in enumerate(letters):
29 ...
30
31# Adding items
32letters.append("e")
33letters.insert(0, "-")
34
35# Removing items
36letters.pop()
37letters.pop(0)
38letters.remove("b")
39del letters[0:3]
40
41# Finding items
42if "f" in letters:
43 letters.index("f")
44
45# Sorting lists
46letters.sort()
47letters.sort(reverse=True)
48
49# Custom sorting
50items = [
51 ("Product1", 10),
52 ("Product2", 9),
53 ("Product3", 11)
54]
55
56items.sort(key=lambda item: item[1])
57
58# Map and filter
59prices = list(map(lambda item: item[1], items))
60expensive_items = list(filter(lambda item: item[1] >= 10, items))
61
62# List comprehensions
63prices = [item[1] for item in items]
64expensive_items = [item for item in items if item[1] >= 10]
65
66# Zip function
67list1 = [1, 2, 3]
68list2 = [10, 20, 30]
69combined = list(zip(list1, list2)) # [(1, 10), (2, 20)]
70
1first = {1, 2, 3, 4}
2second = {1, 5}
3
4first | second # {1, 2, 3, 4, 5}
5first & second # {1}
6first - second # {2, 3, 4}
7first ^ second # {2, 3, 4, 5}
8
9if 1 in first:
10 ...
11