5 min read
ā¢Question 13 of 41easyTuples in Python
Understanding immutable sequences.
What You'll Learn
- What tuples are and why they're useful
- Creating and accessing tuple elements
- Tuple unpacking and named tuples
- When to use tuples vs lists
Understanding Tuples
Tuples are ordered, immutable sequences in Python. Once created, you cannot modify their contents. They're defined with parentheses () or just commas.
Why use tuples?
- Immutability - Data that shouldn't change
- Performance - Slightly faster than lists
- Hashable - Can be used as dictionary keys
- Semantic - Signal that data is fixed
Creating Tuples
code.pyPython
# Empty tuple
empty = ()
# Tuple with items
fruits = ("apple", "banana", "cherry")
# Single item tuple - COMMA IS REQUIRED!
single = ("apple",) # Tuple
not_tuple = ("apple") # Just a string!
# Without parentheses (tuple packing)
coords = 10, 20, 30
point = 1, 2 # Also a tuple
# From other iterables
from_list = tuple([1, 2, 3])
from_string = tuple("abc") # ('a', 'b', 'c')Accessing Elements
code.pyPython
fruits = ("apple", "banana", "cherry", "date")
# Indexing
fruits[0] # "apple"
fruits[-1] # "date"
# Slicing (returns new tuple)
fruits[1:3] # ("banana", "cherry")
fruits[:2] # ("apple", "banana")
fruits[::2] # ("apple", "cherry")
# Membership
"banana" in fruits # True
# Length
len(fruits) # 4Tuple Unpacking
code.pyPython
# Basic unpacking
x, y, z = (1, 2, 3)
print(x, y, z) # 1 2 3
# Swap values
a, b = b, a
# Extended unpacking
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
first, *middle, last = (1, 2, 3, 4, 5)
print(middle) # [2, 3, 4]
# Ignore values with _
x, _, z = (1, 2, 3) # Ignore middle value
# Function returns
def get_user():
return "Alice", 25, "NYC"
name, age, city = get_user()Named Tuples
For more readable code with named fields:
code.pyPython
from collections import namedtuple
# Define a named tuple type
Point = namedtuple('Point', ['x', 'y'])
Person = namedtuple('Person', 'name age city')
# Create instances
p = Point(10, 20)
user = Person("Alice", 25, "NYC")
# Access by name or index
print(p.x, p.y) # 10 20
print(p[0], p[1]) # 10 20
print(user.name) # Alice
# Still immutable
# p.x = 30 # AttributeError!
# Convert to dict
user._asdict() # {'name': 'Alice', 'age': 25, 'city': 'NYC'}Tuple vs List
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Syntax | () | [] |
| Hashable | Yes (can be dict key) | No |
| Performance | Slightly faster | Slightly slower |
| Use case | Fixed data | Dynamic data |
code.pyPython
# Use TUPLE for:
coordinates = (10, 20) # Fixed point
rgb_color = (255, 128, 0) # Fixed color
db_record = ("Alice", 25) # Database row
# Use LIST for:
shopping_cart = ["item1"] # Will add/remove
user_input = [] # Collect dataInterview Tip
When asked about tuples:
- Immutable, ordered sequences
- Faster than lists, use less memory
- Can be dictionary keys (hashable)
- Use for fixed data that shouldn't change
- Know tuple unpacking and named tuples