7. Lists, Tuples, and Sets
What Are Collections in Python?
So far, we've worked with single values like strings and numbers. But what if you want to store multiple values together—like a list of students or favorite colors? That's where Python collection types come in.
In this lesson, we’ll cover three important built-in collections:
- Lists – ordered and changeable
- Tuples – ordered but not changeable
- Sets – unordered and unique values
Lists
A list is used to store multiple items in a single variable. Lists are changeable, meaning you can add, remove, or modify elements.
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple', 'banana', 'cherry']List Operations
# Access items
print(fruits[0]) # apple
# Modify items
fruits[1] = "orange"
# Add items
fruits.append("mango")
fruits.insert(1, "blueberry")
# Remove items
del fruits[2]
fruits.remove("mango")
Tuples
Tuples are like lists, but **they cannot be changed** after creation. Use tuples when you want a collection of data that should not be modified.
colors = ("red", "green", "blue")
print(colors[0]) # redTuples are faster and more memory-efficient than lists, which makes them perfect for **fixed data**.
Sets
A set is a collection that stores **unique values** and does **not keep order**.
numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}Sets are great for removing duplicates or performing mathematical set operations like union and intersection.
evens = {2, 4, 6}
odds = {1, 3, 5}
primes = {2, 3, 5}
print(evens.union(odds)) # {1, 2, 3, 4, 5, 6}
print(evens.intersection(primes)) # {2}When Should You Use Each?
| Type | Ordered? | Changeable? | Allows Duplicates? | Best For |
|---|---|---|---|---|
| List | Yes | Yes | Yes | General data storage |
| Tuple | Yes | No | Yes | Fixed data |
| Set | No | Yes | No | Unique items and fast lookups |
Mini Exercise
Create a list of three favorite foods. Update the second item, add a new item, and remove one item.
# Your turn!
favorite_foods = ["rice", "pizza", "pasta"]
# 1. Change one item
# 2. Add a new item
# 3. Remove one item
print(favorite_foods)