A tuple is a built-in data structure in Python that is used to store multiple items in a single variable. Tuples are ordered, indexed, and immutable, meaning that once they are created, their elements cannot be changed, added, or removed.
Defining a Tuple
Tuples are defined by enclosing elements in parentheses ( ), separated by commas.
# Creating a tuple with multiple elements my_tuple = (1, 2, 3, 4, 5) print(my_tuple) # (1, 2, 3, 4, 5) # Tuple with mixed data types mixed_tuple = (1, "Hello", 3.14, True) print(mixed_tuple) # (1, 'Hello', 3.14, True) # Tuple with one element # (Note: A trailing comma is needed for a single-element tuple) single_element_tuple = (42,) print(single_element_tuple) # (42,)
Immutability in Tuples
A tuple is immutable, which means that once it is created, you cannot modify, add, or remove elements. This makes tuples different from lists, which are mutable and allow modifications.
my_tuple = (1, 2, 3) my_tuple[1] = 10 # TypeError: 'tuple' object does not support item assignment
- Why Are Tuples Immutable?
Tuple Operations
- Indexing and Slicing
Tuples support indexing (both positive and negative) and slicing, just like lists.
my_tuple = (10, 20, 30, 40, 50) # Accessing elements using positive index print(my_tuple[1]) # 20 # Accessing elements using negative index print(my_tuple[-1]) # 50 # Slicing a tuple print(my_tuple[1:4]) # (20, 30, 40)
- Tuple Concatenation and Repetition
Even though tuples are immutable, you can concatenate and repeat them to create new tuples.
tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) # Concatenation new_tuple = tuple1 + tuple2 print(new_tuple) # (1, 2, 3, 4, 5, 6) # Repetition repeated_tuple = tuple1 * 3 print(repeated_tuple) # (1, 2, 3, 1, 2, 3, 1, 2, 3)
- Tuple Methods
Tuples have only two built-in methods:
my_tuple = (1, 2, 3, 2, 4, 2, 5) # Count occurrences of an element print(my_tuple.count(2)) # 3 # Find index of an element print(my_tuple.index(3)) # 2
Tuple Packing and Unpacking
Tuples allow packing multiple values into a single variable and unpacking them into separate variables.
# Packing person = ("Alice", 25, "Engineer") # Unpacking name, age, profession = person print(name) # Alice print(age) # 25 print(profession) # Engineer
Tuple vs. List: Key Differences
- Syntax
Tuple: (1, 2, 3)
List: [1, 2, 3]
- Mutability
Tuple: Immutable
List: Mutable
- Performance
Tuple: Faster
List: Slower
- Memory Usage
Tuple: Less
List: More
- Methods
Tuple: Fewer (count(), index())
List: More (e.g., append(), remove())
- Hashable (Can be dictionary keys)?
Tuple: Yes (if all elements are hashable)
List: No
When to Use Tuples?
coordinates = { (40.7128, -74.0060): "New York", (34.0522, -118.2437): "Los Angeles" } print(coordinates[(40.7128, -74.0060)]) # New York