A Python tuple
is a collection of ordered, immutable, and heterogeneous elements.
- Ordered Collection -
Tuples
maintain the order of elements as they are defined. - Immutable - Once a tuple is created, its elements cannot be changed, added, or removed. However, if an element is mutable (like a list), the contents of that element can be modified.
- Heterogeneous Elements - A tuple can contain elements of different data types (e.g., integers, floats, strings)
Creating a Tuple:Python Tuple, ordered, immutable, heterogeneous .
# Tuple of integers tuple1 = (1, 2, 3) print(tuple1) # Output: (1, 2, 3) # Tuple of mixed data types tuple2 = ('apple', 3.14, 5) print(tuple2) # Output: ('apple', 3.14, 5)
Accessing Elements:
tuple1 = (1, 2, 3) print(tuple1[0]) # Accessing the first element, Output: 1 print(tuple1[1:]) # Slicing, Output: (2, 3)
Immutable Nature:
tuple1 = (1, 2, 3) # This will cause an error: # tuple1[0] = 4 # TypeError: 'tuple' object does not support item assignment # However, you can create a new tuple with modified elements tuple1_modified = (4,) + tuple1[1:] print(tuple1_modified) # Output: (4, 2, 3)
Tuple with Mutable Element:
# Tuple with a list as an element tuple_with_list = ([1, 2, 3], 'hello') print(tuple_with_list) # Output: ([1, 2, 3], 'hello') # Modifying the mutable element inside the tuple tuple_with_list[0].append(4) print(tuple_with_list) # Output: ([1, 2, 3, 4], 'hello')
Tuple with Mutable Elements:
# Tuple with a list as an element tuple_with_list = ([1, 2, 3], 'hello') print(tuple_with_list) # Output: ([1, 2, 3], 'hello') # Modifying the mutable element inside the tuple tuple_with_list[0].append(4) print(tuple_with_list) # Output: ([1, 2, 3, 4], 'hello')
Tuple Unpacking:
tuple3 = ('a', 'b', 'c') x, y, z = tuple3 print(x) # Output: 'a' print(y) # Output: 'b' print(z) # Output: 'c'
Tuples are commonly used for returning multiple values from functions, as dictionary keys
(since they are immutable), and in situations where immutability and order preservation are desired properties.