Python Tuples
4 min read ·
Tuples are one of the core data structures in Python.
They are used to store multiple items in a single variable, similar to lists, but with one key difference: tuples are immutable.
This makes tuples faster, safer, and ideal for fixed data.
What Is a Tuple?
A tuple is a collection that:
- Is ordered
- Is immutable (cannot be changed)
- Allows duplicate values
- Can store different data types
Tuple vs List (Core Difference)
| Feature | List | Tuple |
|---|---|---|
| Syntax | [] | () |
| Mutable | Yes | No |
| Performance | Slower | Faster |
| Use case | Dynamic data | Fixed data |
Creating Tuples
Using Parentheses
Tuple with One Item (Important)
A single-item tuple must have a comma.
Without comma:
Using tuple() Constructor
Access Tuple Items (Indexing)
Tuples use zero-based indexing, same as lists.
Access Tuple Items (Slicing)
Tuple Is Immutable (Key Concept)
Once created, tuple items cannot be changed.
Loop Through a Tuple
Using for Loop
Using Index
Check If Item Exists
Tuple Length
Allow Duplicate Values
Nested Tuples
Tuples can contain other tuples.
Tuple Packing and Unpacking
Packing
Unpacking
Extended Unpacking
Change Tuple Values (Indirect Way)
Since tuples are immutable, convert to list → modify → convert back.
Add Items to a Tuple (Indirect Way)
Remove Items from a Tuple (Indirect Way)
Delete a Tuple Completely
Tuple Methods
Tuples have only two built-in methods.
| Method | Description |
|---|---|
count() | Counts occurrences of a value |
index() | Returns index of a value |
count()
index()
Tuple with Functions (Common Use)
Functions often return tuples.
When to Use Tuples
Use tuples when:
- Data should not change
- You want faster access
- Data represents a fixed structure
- Returning multiple values from functions