What are tuples?
Tuples are like lists, but they can’t be changed once created. They’re immutable (unchangeable) sequences. Use tuples for data that shouldn’t change:- Coordinates (x, y)
- RGB colors (255, 0, 0)
- Database records
- Function return values
Creating tuples
Accessing items
Just like lists, tuples use indexing:Tuple unpacking
Python’s coolest tuple feature:Tuple Operations
Since tuples are sequences, you can perform several read-only operations on them:1. Indexing & Slicing
Access individual items or ranges of items just like lists:2. Membership Checking (in)
Check if an item exists inside a tuple quickly:
3. Sorting with sorted()
Tuples do not have a .sort() method because they are immutable. However, you can pass a tuple to the built-in sorted() function, which returns a new sorted list:
Importance of Tuples
- Data Integrity (Safety): By making a collection immutable, you guarantee that other parts of your program cannot accidentally modify, append, or delete its values.
- Performance: Tuples are stored in a single memory block, making them slightly faster to create and access than lists, and they consume less memory.
- Dictionary Keys: Because tuples are immutable, they are hashable. This means you can use a tuple as a key in a dictionary (e.g. mapping coordinates to locations), which is not possible with lists.
When to use a Tuple vs a List
- Use a Tuple when:
- The data is fixed and should never change throughout the execution of the program (e.g., GPS coordinates, RGB values, database config keys).
- You want to return multiple values from a function.
- You need to use the collection as a key in a dictionary.
- Use a List when:
- You have a collection of homogeneous items that will grow, shrink, or change over time (e.g. a shopping cart, a list of users).
Common mistakes
Forgetting comma in single tuple
Forgetting comma in single tuple
Trying to modify tuples
Trying to modify tuples
Practice & Exercises
To reinforce what you’ve learned in this section (Tuples, immutability, and conversions), practice with these interactive notebooks:Follow-Along Practice
Practice initializing tuples, accessing elements, and working with immutability.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises on coordinate systems and tuple conversions.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now let’s learn about Dictionaries - perfect for storing key-value pairs!Dictionaries
Learn about key-value pairs