Section Overview
In this section, you will learn about two important collection types in Python beyond lists and dictionaries: tuples and sets. Tuples are like lists but immutable, and sets store unique items without order.
By the end of this section, you should be able to:
- Understand what tuples are and how to create them
- Use tuples for fixed collections of data
- Understand what sets are and their properties
- Perform basic operations with sets
Lesson 1: Tuples – Immutable Sequences
Tuples are defined with parentheses ()
and cannot be changed after creation:
coordinates = (10, 20)
print(coordinates[0]) # Outputs: 10
Because tuples are immutable, you cannot add or remove items:
# coordinates[0] = 15 # This would cause an error
Tuples are useful for fixed data like RGB colors, geographic coordinates, or function returns.
Lesson 2: Sets – Collections of Unique Items
Sets are unordered collections of unique elements, created with curly braces {}
or set()
:
fruits = {"apple", "banana", "orange"}
print(fruits)
Duplicates are automatically removed:
numbers = {1, 2, 2, 3}
print(numbers) # Outputs: {1, 2, 3}
Lesson 3: Basic Set Operations
You can add or remove items, and perform operations like union and intersection:
fruits.add("kiwi")
fruits.remove("banana")
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5} print(a.intersection(b)) # {3} print(a.difference(b)) # {1, 2}
Quiz: Check Your Understanding
1. Can you change the items in a tuple after creation?
Answer: No, tuples are immutable.
2. How do sets handle duplicate values?
Answer: They automatically remove duplicates.
3. What does the .union()
method do on sets?
Answer: Combines all unique elements from both sets.
4. What data type would you use for a fixed collection of values that should not change?
Answer: Tuple
Practice Exercise: Using Tuples and Sets
- Create a tuple to represent a point
(x, y)
with values (5, 10)
- Create a set of colors:
"red"
, "green"
, "blue"
, "red"
- Print the tuple and the set
- Add
"yellow"
to the set and print it again
Starter code:
point = (5, 10)
colors = {"red", "green", "blue", "red"}
print("Point:", point)
print("Colors:", colors)
colors.add("yellow")
print("Updated colors:", colors)