Intermediate Topic 22 of 54 Programming Fundamentals
Tuples
Fixed-size immutable ordered groupings of values.
How it works
A tuple groups a fixed number of values, typically immutable, and supports unpacking such as x, y = point. Elements may have different types and are accessed by position. Because they cannot change after creation, tuples are hashable when their elements are, making them valid dictionary keys and set members.
Step-by-step walkthrough
- A tuple groups values in a fixed order.
- Fields are read by position, t[1] is 30.
- Assigning t[1] = 31 raises an error because tuples cannot change.
- Because they are immutable, tuples can be dictionary keys.
- Build a new tuple to change a value.
Where it is used
Returning multiple values from a function, representing coordinates or RGB colors, keeping records in a database row-like form and using composite keys in maps are common uses. Tuples signal that the data is fixed.
Common pitfall
Trying to modify a tuple raises an error; for evolving data use a list or an object. Positional access like t[3] is unreadable when tuples grow long, so switch to named tuples, records or classes. A tuple holding a list is only shallowly immutable.
Where it fits in the course
Tuples is topic 22 of 54 in Programming Fundamentals, rated Intermediate. It follows Sets. The next topic is Recursion.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Tuples?
Where do people use Tuples?
What is the most common mistake with Tuples?
What should I learn before this topic?
How can I practice it?
Is Tuples hard to learn?
How long does it take to learn Tuples?
Which topics are related to Tuples?
What should I study after Tuples?
Related topics
- Sets (Programming Fundamentals)
- Recursion (Programming Fundamentals)
- Dictionaries and Maps (Programming Fundamentals)
- Base Case (Programming Fundamentals)