Data structures: list, tuple, dict, set
Lists, tuples, dictionaries, sets and sequences.
All lessons · Python lessons: learn from scratch
Lists
A list is an ordered, changeable collection. Indexes start at 0 and negative indexes count from the end. A slice a[1:4] takes a part.
tasks = ["read", "code", "walk"]
tasks.append("sleep")
tasks.insert(0, "wake")
tasks.remove("walk")
print(tasks) # ['wake', 'read', 'code', 'sleep']
print(tasks[-1], tasks[1:3])
print(sorted([5, 2, 9]), len(tasks))A list comprehension is a compact form: [x * x for x in range(5) if x % 2 == 0].
squares = [n * n for n in range(1, 6)] print(squares) # [1, 4, 9, 16, 25]
Tuples and dictionaries
A tuple is an ordered collection that cannot change; good for fixed data like coordinates. A dict stores key–value pairs and finds a value by key very quickly.
point = (40.4, 49.8)
lat, lon = point # unpacking
phone = {"Ali": "055-111", "Nigar": "050-222"}
phone["Orkhan"] = "070-333"
print(phone.get("Zaur", "unknown"))
for name, num in phone.items():
print(name, num)Sets and choosing
A set holds unique elements and is ideal for finding shared or different items: & intersection, | union, - difference.
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a & b, a | b, a - b)
print(list({"x", "y", "x"})) # duplicates vanish- Order and duplicates matter: list.
- A fixed group: tuple.
- Looking up by key: dict.
- Uniqueness and set operations: set.