So far: one variable = one value.
Problem: Want to store 1000 students → 1000 variables? 😱
Solution: Collections — lists and dictionaries for storing multiple pieces of data!
📋 Lists — ordered collections
A list is a sequence of elements stored under one name.
Creating lists:
# Empty list:
empty_list = []
# List of numbers:
numbers = [1, 2, 3, 4, 5]
# List of strings:
fruits = ["apple", "banana", "orange"]
# Mixed list (different types):
mixed = ["text", 42, True, 3.14, [1, 2, 3]]
Accessing elements (indexing):
⚠️ IMPORTANT: Indexes start at 0!
fruits = ["apple", "banana", "orange"]
# 0 1 2
print(fruits[0]) # apple (first!)
print(fruits[1]) # banana
print(fruits[2]) # orange
print(fruits[-1]) # orange (last)
print(fruits[-2]) # banana (second to last)
Modifying elements:
fruits[1] = "pear" # Replace the second element
print(fruits) # ["apple", "pear", "orange"]
List length:
print(len(fruits)) # 3 elements
➕ Adding and removing elements
append() — add to the end:
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # ["apple", "banana", "orange"]
fruits.append("pear")
print(fruits) # ["apple", "banana", "orange", "pear"]
insert() — insert at a position:
fruits = ["apple", "orange"]
fruits.insert(1, "banana") # Insert at index 1
print(fruits) # ["apple", "banana", "orange"]
remove() — remove by value:
fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits) # ["apple", "orange"]
Removes the first occurrence!
pop() — remove by index (and return the value):
fruits = ["apple", "banana", "orange"]
# Remove the last element:
last = fruits.pop()
print(last) # orange
print(fruits) # ["apple", "banana"]
# Remove by index:
first = fruits.pop(0)
print(first) # apple
print(fruits) # ["banana"]
clear() — clear the entire list:
fruits.clear()
print(fruits) # []
🔪 Slicing — subsets of a list
Syntax: list[start:end:step]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Elements from index 2 up to (not including) 5:
print(numbers[2:5]) # [2, 3, 4]
# From the beginning up to index 5:
print(numbers[:5]) # [0, 1, 2, 3, 4]
# From index 5 to the end:
print(numbers[5:]) # [5, 6, 7, 8, 9]
# All elements (a copy):
print(numbers[:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Every second element:
print(numbers[::2]) # [0, 2, 4, 6, 8]
# Every third element:
print(numbers[::3]) # [0, 3, 6, 9]
# Reverse the list:
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Last 3 elements:
print(numbers[-3:]) # [7, 8, 9]
# First 3 elements:
print(numbers[:3]) # [0, 1, 2]
Slices create a NEW list — the original is not modified!
🔧 Useful list methods
sort() — sort in place:
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 9]
# Reverse sort:
numbers.sort(reverse=True)
print(numbers) # [9, 5, 4, 3, 2, 1, 1]
reverse() — reverse in place:
letters = ['A', 'B', 'C', 'D']
letters.reverse()
print(letters) # ['D', 'C', 'B', 'A']
count() — count occurrences:
numbers = [1, 2, 3, 2, 4, 2, 5]
print(numbers.count(2)) # 3 (the value 2 appears three times)
index() — find the index of an element:
fruits = ["apple", "banana", "orange"]
index = fruits.index("banana")
print(index) # 1
extend() — add multiple elements:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
Membership test (in):
fruits = ["apple", "banana", "orange"]
if "banana" in fruits:
print("We have bananas!") # Prints
if "pear" not in fruits:
print("No pears") # Prints
📖 Dictionaries — key-value pairs
Lists: access by index (0, 1, 2…)
Dictionaries: access by key (name, age, email…)
Creating dictionaries:
# Empty dictionary:
empty_dict = {}
# Dictionary with data:
student = {
"name": "Anna",
"age": 16,
"city": "Moscow",
"grade": 10
}
# Keys can be strings or numbers:
scores = {
1: 100,
2: 85,
3: 92
}
Accessing values:
student = {
"name": "Anna",
"age": 16,
"city": "Moscow"
}
print(student["name"]) # Anna
print(student["age"]) # 16
print(student["city"]) # Moscow
Modifying values:
student["age"] = 17
student["grade"] = 11
print(student) # Age and grade updated!
Adding new keys:
student["email"] = "anna@example.com"
student["phone"] = "+1-123-456-7890"
print(student) # email and phone added
Removing keys:
# del — remove a key:
del student["phone"]
# pop() — remove and return the value:
email = student.pop("email")
print(email) # anna@example.com
print(student) # email removed
🔑 Dictionary methods
get() — safe lookup (no KeyError):
student = {"name": "Anna", "age": 16}
# Direct access (can raise KeyError):
print(student["email"]) # ❌ KeyError!
# Safe access:
email = student.get("email", "No email")
print(email) # "No email" (default value)
age = student.get("age", 0)
print(age) # 16 (key exists)
keys() — all keys:
student = {"name": "Anna", "age": 16, "city": "Moscow"}
keys = student.keys()
print(keys) # dict_keys(['name', 'age', 'city'])
print(list(keys)) # ['name', 'age', 'city']
values() — all values:
values = student.values()
print(values) # dict_values(['Anna', 16, 'Moscow'])
print(list(values)) # ['Anna', 16, 'Moscow']
items() — key-value pairs:
items = student.items()
print(items)
# dict_items([('name', 'Anna'), ('age', 16), ('city', 'Moscow')])
# Iteration:
for key, value in student.items():
print(f"{key}: {value}")
# name: Anna
# age: 16
# city: Moscow
update() — update multiple keys:
student = {"name": "Anna", "age": 16}
student.update({
"age": 17,
"city": "Moscow",
"grade": 11
})
print(student)
# {"name": "Anna", "age": 17, "city": "Moscow", "grade": 11}
clear() — clear the dictionary:
student.clear()
print(student) # {}
Checking key membership:
if "name" in student:
print("Name is present!")
if "email" not in student:
print("No email field")
🔄 Iterating over lists and dictionaries
Lists:
fruits = ["apple", "banana", "orange"]
# Simple iteration:
for fruit in fruits:
print(fruit)
# With index (enumerate):
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: orange
# Starting index at 1:
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. orange
Dictionaries:
student = {"name": "Anna", "age": 16, "city": "Moscow"}
# Keys only:
for key in student:
print(key)
# name
# age
# city
# Values only:
for value in student.values():
print(value)
# Anna
# 16
# Moscow
# Keys and values:
for key, value in student.items():
print(f"{key}: {value}")
# name: Anna
# age: 16
# city: Moscow
🎯 Practical examples
1. TODO list:
tasks = []
# Adding:
tasks.append("Study")
tasks.append("Exercise")
tasks.append("Reading")
# Displaying:
print("📝 My tasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
# Removing:
tasks.remove("Exercise")
# Checking:
if "Study" in tasks:
print("Study is still pending!")
2. Vote counting:
votes = ["Python", "JavaScript", "Python", "Java", "Python", "JavaScript"]
# Count:
vote_count = {}
for vote in votes:
if vote in vote_count:
vote_count[vote] += 1
else:
vote_count[vote] = 1
print(vote_count)
# {'Python': 3, 'JavaScript': 2, 'Java': 1}
# Winner:
winner = max(vote_count, key=vote_count.get)
print(f"Winner: {winner}")
3. Student database:
students = [
{"name": "Anna", "age": 16, "grade": 10},
{"name": "Bob", "age": 17, "grade": 11},
{"name": "Sveta", "age": 16, "grade": 10}
]
# Display all:
for student in students:
print(f"{student['name']}, age {student['age']}, grade {student['grade']}")
# Search:
search_name = "Anna"
for student in students:
if student["name"] == search_name:
print(f"Found: {student}")
break
# Filter by grade:
grade_10 = [s for s in students if s["grade"] == 10]
print(f"Grade 10: {len(grade_10)} students")
4. Game inventory:
inventory = {
"sword": 1,
"shield": 1,
"health potion": 5,
"mana potion": 3,
"gold": 150
}
# Display inventory:
print("🎒 Inventory:")
for item, count in inventory.items():
print(f" {item}: {count}")
# Using an item:
if inventory["health potion"] > 0:
inventory["health potion"] -= 1
print("🧪 Used a health potion!")
print(f"Remaining: {inventory['health potion']}")
# Adding gold:
inventory["gold"] += 50
print(f"💰 Gold: {inventory['gold']}")
📚 Nested structures
List of dictionaries:
users = [
{"username": "anna", "age": 16, "city": "Moscow"},
{"username": "bob", "age": 18, "city": "SPb"},
{"username": "charlie", "age": 17, "city": "Moscow"}
]
# Access:
print(users[0]["username"]) # anna
print(users[1]["age"]) # 18
# Find users from Moscow:
moscow_users = [u for u in users if u["city"] == "Moscow"]
print(f"From Moscow: {len(moscow_users)}")
Dictionary of lists:
courses = {
"python": ["Anna", "Bob", "Sveta"],
"javascript": ["Pete", "Mary"],
"java": ["Ivan", "Kate", "Alex"]
}
# Access:
print(courses["python"]) # ['Anna', 'Bob', 'Sveta']
print(courses["python"][0]) # Anna
# Add a student:
courses["python"].append("New Student")
# Number of students per course:
for course, students in courses.items():
print(f"{course}: {len(students)} students")
Dictionary of dictionaries:
contacts = {
"anna": {
"phone": "+1-123-456",
"email": "anna@mail.com",
"city": "Moscow"
},
"bob": {
"phone": "+1-987-654",
"email": "bob@mail.com",
"city": "SPb"
}
}
# Access:
print(contacts["anna"]["email"]) # anna@mail.com
print(contacts["bob"]["phone"]) # +1-987-654
# Add a new contact:
contacts["charlie"] = {
"phone": "+1-555-123",
"email": "charlie@mail.com",
"city": "Kazan"
}
⚠️ Common mistakes
1. IndexError — out of bounds:
fruits = ["apple", "banana"]
print(fruits[2]) # ❌ IndexError!
# Fix — check first:
if len(fruits) > 2:
print(fruits[2])
2. KeyError — key not found:
student = {"name": "Anna"}
print(student["age"]) # ❌ KeyError!
# Fix — use get():
age = student.get("age", 0)
print(age) # 0
3. Modifying a list while iterating:
# ❌ Dangerous:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # May skip elements!
# ✅ Correct — build a new list:
numbers = [1, 2, 3, 4, 5]
odd_numbers = [n for n in numbers if n % 2 != 0]
print(odd_numbers) # [1, 3, 5]
4. Copying lists:
# ❌ Reference, not a copy:
list1 = [1, 2, 3]
list2 = list1
list2[0] = 999
print(list1) # [999, 2, 3] — changed!
# ✅ Actual copy:
list1 = [1, 2, 3]
list2 = list1.copy() # or list1[:]
list2[0] = 999
print(list1) # [1, 2, 3] — unchanged!
🚀 Summary
Lists and dictionaries are the backbone of data handling!
You’ve learned to:
✅ Create and use lists
✅ Add, remove, and modify elements
✅ Use slicing to extract subsets
✅ Work with dictionaries (key-value pairs)
✅ Apply list and dictionary methods
✅ Iterate over collections
✅ Build nested data structures
With collections you can:
- Store any amount of data
- Organize complex structures
- Build in-memory databases
- Process large volumes of information
- Solve real-world problems
Practice in CodeHS! Build:
- TODO lists
- Address books
- Student databases
- Game inventories
- Statistics and analytics
Collections are everywhere: files, databases, APIs, web development, data science! 💪
Next step: Explore file I/O and Python libraries! 📂
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!