chapter 6.1

Lists & Collections

Organizing data with lists, tuples, dicts, and sets

So far you've stored single values in variables. Collections let you group multiple values together. Python has four built-in collection types, each with different strengths.
Lists — ordered, mutable (you can change them). The workhorse collection:
fruits = ["apple", "banana", "cherry"]
print(fruits[0])        # "apple" (first item)
print(fruits[-1])       # "cherry" (last item)

fruits.append("mango")  # Add to end
fruits[1] = "blueberry" # Replace item at index 1
print(fruits)           # ['apple', 'blueberry', 'cherry', 'mango']
print(len(fruits))      # 4
warning
Aliasing trap: list_b = list_a does NOT copy the list — both names point to the same data. Change one, both change. To copy: list_b = list_a.copy() or list_b = list_a[:].
Tuples — ordered, immutable (can't change after creation). Use when data shouldn't be modified:
coordinates = (10, 20)
x, y = coordinates    # Tuple unpacking
print(f"x={x}, y={y}")

# Can't do: coordinates[0] = 99  → TypeError!
Dictionaries — key-value pairs. Look up data by a meaningful name instead of a number:
user = {
    "name": "Ada",
    "age": 28,
    "language": "Python"
}

print(user["name"])          # "Ada"
print(user.get("email", "N/A"))  # "N/A" (no crash if missing)

user["level"] = "intermediate"   # Add new key

for key, value in user.items():
    print(f"  {key}: {value}")
Sets — unordered, unique values only. Great for membership testing and removing duplicates:
numbers = {1, 2, 3, 2, 1}
print(numbers)  # {1, 2, 3} — duplicates removed

print(3 in numbers)   # True  (fast lookup)
print(99 in numbers)  # False
List comprehensions — a compact way to build lists from loops:
# Instead of:
squares = []
for x in range(1, 6):
    squares.append(x ** 2)

# You can write:
squares = [x ** 2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# With a filter:
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]
your turn
challenge

Create a dictionary of 3 students and their scores. Loop through it and print each name and score. Then use a list comprehension to create a list of names who scored 90 or above.

loading editor...

output
$ Press RUN to execute your code
AI Tutor

Ask about Lists & Collections

Hey! I'm your AI tutor.

Ask me anything about this lesson, or paste code you're stuck on.

AI tutor is a premium feature