Python: Tuples
Discover Python's immutable sequences. Tuples are perfect for grouping related data that shouldn't change, offering better performance and data integrity compared to lists.
Creating Tuples
A tuple is a collection that is ordered and immutable. Tuples are written with round brackets ( ). While the parentheses are technically optional in many cases, they are used by convention for clarity.
The Single-Item Tuple Trap
Creating a tuple with one item requires a trailing comma.
- x = (5) is treated as an integer in parentheses: 5
- x = (5,) is a tuple containing one item: (5,)
- Tuples can hold mixed data types, just like lists
Tuple Basics
PythonDefining tuples with various configurations.
Accessing and Slicing
Tuple elements are accessed by index, starting at 0. They support negative indexing and slicing in the exact same way as lists and strings.
Navigating Tuples
PythonUsing indices and slices to retrieve data.
Tuple Immutability
The defining characteristic of a tuple is that it cannot be changed after creation. You cannot add, remove, or replace items. This provides a safety guarantee: if you pass a tuple to a function, you know the function cannot alter your original sequence.
Consistency and Errors
PythonAttempts to mutate a tuple will fail.
Tuple Methods: count and index
Because tuples are immutable, they only have two built-in methods:count()and index().
Limited Methods
PythonSimple search and counting operations.
Tuple Packing and Unpacking
Packing is when you put multiple values into a single tuple.Unpacking is the process of extracting those values into multiple variables. This is often used to swap variables or extract data from structured sequences.
Destructuring Data
PythonAssigning tuple items to individual variables.
Extended Unpacking with *
Sometimes you want to unpack a few items and capture the rest in a list. The *syntax allows you to handle variable-length sequences gracefully.
Handling Remainders
PythonCapturing leftover items during unpacking.
Tuple vs List
Choosing between a list and a tuple depends on your intent. Lists are for collections of similar items that change (like a shopping list). Tuples are typically for groups of related but different data points (like an address or coordinate).
Comparison Table
When to use which?
- Complexity: Tuples are simpler and slightly faster for iteration/memory.
- Integrity: Tuples prevent accidental changes to your data.
- Semantics: Use Lists for homogeneous data; use Tuples for heterogeneous records.
- Functionality: Lists have many methods (sort, append, etc.); Tuples have almost none.
Named Tuples (collections.namedtuple)
Named tuples allow you to access elements by a descriptive name using dot notation, as well as by their index. They are part of the collections module.
Descriptive Sequences
PythonA lightweight alternative to full classes.
Returning Multiple Values
In Python, functions can seemingly return multiple values. In reality, the function is returning a single tuple containing those values, which you then unpack at the call site.
Functions and Tuples
PythonEasily passing back several results.
Nested Tuples
Tuples can contain other tuples as elements. This is useful for representing records within records, such as a list of geographic coordinates or database rows.
Hierarchy with Tuples
PythonStructuring complex relationships.
Quiz - Test Your Knowledge
Check your mastery of Python tuples by answering these eight questions. Focus on the core differences between tuples and lists, and keep the single-item tuple rule in mind.
Knowledge Check
1. How do you create a tuple with exactly one item?
2. Which statement about tuples is correct?
3. What is the output of a, *b, c = [1, 2, 3, 4, 5]?
4. Which method returns the number of times a value appears in a tuple?
5. Can you change an element inside a list that is itself inside a tuple?
6. What is a Named Tuple?
7. Which tool is used to create Named Tuples?
8. What happens if you try to do my_tuple[0] = 10?