In Python, a tuple is an ordered collection of elements, similar to a list, but unlike lists, tuples are immutable. Once a tuple is created, its elements cannot be modified, added, or removed. Tuples are often used for fixed collections of items.
Creating a tuple:
You can create a tuple by placing comma-separated values inside parentheses.
my_tuple = (1, 2, 3)
print(my_tuple)
Key features of tuples:
- Immutable: Once created, the values inside a tuple cannot be changed.
- Ordered: Elements maintain the order in which they are defined.
- Allow duplicates: Tuples can contain duplicate elements.
- Can store different data types: You can store multiple data types in a single tuple.
Accessing elements:
You can access elements of a tuple using indexing, similar to lists.
my_tuple = (10, 20, 30)
print(my_tuple[0]) # Output: 10
print(my_tuple[1]) # Output: 20
Slicing a tuple:
You can slice a tuple to get a part of it.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
Tuple operations:
Tuples support operations like concatenation and repetition.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenation
print(tuple1 + tuple2) # Output: (1, 2, 3, 4, 5, 6)
# Repetition
print(tuple1 * 3) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Tuple packing and unpacking:
- Packing: Creating a tuple by grouping values together.
- Unpacking: Assigning elements of a tuple to individual variables.
# Packing
my_tuple = (1, 2, 3)
# Unpacking
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
Example use cases:
- Storing related values together (e.g., coordinates
(x, y)
). - Returning multiple values from a function.
- Using tuples as keys in dictionaries (because they are immutable)