Today you will learn:
By the end, you will be able to store complex collections of data and access them efficiently.
A list can contain other lists.
This is useful for storing multidimensional data, e.g., a color palette:
colors = [["red", "darkred"], ["green", "lightgreen"], ["blue", "lightblue"]]
print(colors[0][1])
Output:
darkred
Explanation:
colors[0] → first list: ["red", "darkred"]colors[0][1] → second element of this list: "darkred"Practical tip:
Nested lists are ideal for tables or grouped values.
You can use nested loops to read all values:
for color_group in colors:
for color in color_group:
print(color)
Lists can be sorted, reversed, or filtered for specific elements.
Sort ascending:
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)
Output:
[1, 2, 5, 9]
Reverse order:
numbers_reversed = list(reversed(numbers))
print(numbers_reversed)
Output:
[9, 5, 2, 1]
Filter using loops or list comprehensions:
Only even numbers:
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
Output:
[2]
Practical tip:
sort() modifies the original listsorted(list) → creates a new sorted listreversed() → just reverses order, does not sortA dictionary can contain other dictionaries to store complex information.
people = {
"Max": {"age": 20, "city": "Berlin"},
"Anna": {"age": 25, "city": "Hamburg"}
}
print(people["Max"]["city"])
Output:
Berlin
Explanation:
Iterating over nested dictionaries:
for name, data in people.items():
print(name, "lives in", data["city"], "and is", data["age"], "years old")
Output:
Max lives in Berlin and is 20 years old
Anna lives in Hamburg and is 25 years old
Create a shopping list that contains different categories: fruits, vegetables, drinks.
Example structure:
shopping_list = {
"Fruits": ["Apple", "Banana"],
"Vegetables": ["Carrot", "Bell Pepper"],
"Drinks": ["Water", "Juice"]
}
Print all items, e.g., using loops.
Add a new category or a new product.
Create a dictionary for 3 pets. Each pet has: Name, Type, Age.
Example:
pets = {
"Pet1": {"Name": "Bello", "Type": "Dog", "Age": 5},
"Pet2": {"Name": "Miezi", "Type": "Cat", "Age": 3},
"Pet3": {"Name": "Hoppel", "Type": "Rabbit", "Age": 2}
}
for key, pet in pets.items():
print(pet["Name"], "-", pet["Type"])
# Check which pet is older than 3 years
for key, pet in pets.items():
if pet["Age"] > 3:
print(pet["Name"], "is older than 3 years")