Python Tuples, Sets & Dicts
Choose the right Python collection for structured data.
Python provides several built-in data structures to help organize and manage data efficiently. Along with lists, Python offers tuples, sets, and dictionaries. Each structure has unique features and is useful in different situations.
Understanding when to use a tuple, set, or dictionary is an important step toward becoming a better Python programmer. In this lesson, you will learn what they are, how to create them, and when to use each one.
What is a Tuple?
A tuple is an ordered collection of items, similar to a list. The main difference is that tuples are immutable, which means their values cannot be changed after creation. Tuples are written using parentheses.
Creating a Tuple
colors = ("Red", "Green", "Blue")
print(colors)Output
('Red', 'Green', 'Blue')A tuple can contain different data types.
data = ("Python", 3.11, True)Accessing Tuple Items
Like list items, tuple items are accessed with zero-based indexes. Negative indexes count from the end.
colors = ("Red", "Green", "Blue")
print(colors[0])
print(colors[-1])Output
Red
BlueUse slicing to access a range of tuple items.
print(colors[0:2])Output
('Red', 'Green')Why Use Tuples?
Tuples are useful when data should remain unchanged. Because a tuple cannot be modified, it helps prevent accidental changes.
- Days of the week
- Months of the year
- GPS coordinates
- Fixed configuration values
What is a Set?
A set is an unordered collection of unique items. Unlike lists and tuples, sets automatically remove duplicate values. Non-empty sets are written using curly braces.
Creating a Set
numbers = {10, 20, 30, 40}
print(numbers)The displayed order may differ because sets do not maintain a fixed positional order.
Duplicate Values
One of the biggest advantages of sets is that they automatically remove duplicates.
numbers = {10, 20, 20, 30, 30, 40}
print(numbers)Possible Output
{10, 20, 30, 40}This makes sets useful whenever only unique values should be retained.
Adding and Removing Set Items
Add an Item
fruits = {"Apple", "Banana"}
fruits.add("Orange")
print(fruits)Remove an Item
fruits.remove("Banana")
print(fruits)Other useful set methods include discard(), pop(), and clear(). Unlike remove(), discard() does not raise an error when the requested value is absent.
Set Operations
Sets support mathematical operations that are useful when comparing collections.
Union
A union combines every unique value from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)Intersection
An intersection returns values common to both sets.
print(a & b)Difference
A difference returns values that exist only in the first set.
print(a - b)What is a Dictionary?
A dictionary stores data as key-value pairs. Unlike lists or tuples, dictionary values are accessed using keys instead of positional indexes. Dictionaries are written using curly braces, and each key must be unique.
Creating a Dictionary
student = {
"name": "Alice",
"age": 20,
"course": "Python"
}
print(student)Accessing Dictionary Values
Use a key to retrieve its value.
print(student["name"])
print(student["age"])Output
Alice
20The get() method is useful when a key might be missing because it can return None or a chosen default instead of raising KeyError.
print(student.get("course"))Adding and Updating Values
Assign a value to a new key to add a pair. Assign to an existing key to update its value.
student["city"] = "Delhi"
student["age"] = 21
print(student)Removing Dictionary Items
Use pop() to remove a particular key and its value. Other useful methods include popitem() and clear().
student.pop("city")
print(student)Looping Through a Dictionary
Use items() to loop through dictionary keys and values together.
student = {
"name": "Alice",
"age": 20,
"course": "Python"
}
for key, value in student.items():
print(key, ":", value)Output
name : Alice
age : 20
course : PythonWhen Should You Use Each?
| Structure | Use It When |
|---|---|
| List | You need an ordered and changeable collection |
| Tuple | The ordered data should not change |
| Set | You need unique values and positional order is unimportant |
| Dictionary | You need key-value pairs and quick lookup by key |
Choosing the right data structure makes programs more efficient and easier to understand.
Key Takeaways
- A tuple is an ordered, immutable collection of items.
- Tuples use parentheses.
- A set is an unordered collection of unique items.
- Sets automatically remove duplicates and support operations such as union and intersection.
- A dictionary stores data as key-value pairs.
- Dictionary values are accessed using keys instead of indexes.
- Dictionaries make it easy to add, update, retrieve, and remove data.
- Each data structure has a different purpose and should be chosen based on the problem.
- Understanding tuples, sets, and dictionaries helps you write cleaner, faster, and more organized Python programs.