Tuples
What is a Tuple?
A tuple in Python is an ordered, immutable collection of elements. This means that once a tuple is created, its elements cannot be changed, added, or removed. Tuples are defined by enclosing elements within parentheses ().
Creating a Tuple
Python
my_tuple = (1, 2, 3, "apple", True)
Like lists, tuples can contain elements of different data types.
Accessing Tuple Elements
Similar to lists, you can access individual elements using their index:
Python
my_tuple = (10, 20, 30, 40)
first_element = my_tuple[0] # Accesses the first element (10)
third_element = my_tuple[2] # Accesses the third element (30)
Slicing Tuples
You can also use slicing to extract a portion of a tuple:
Python
my_tuple = (10, 20, 30, 40, 50)
subtuple = my_tuple[1:4] # Extracts elements from index 1 to 3 (inclusive)
print(subtuple) # Output: (20, 30, 40)
Immutability
Unlike lists, tuples are immutable. This means you cannot modify their contents after creation.
Python
my_tuple = (10, 20, 30)
my_tuple[1] = 25 # This will raise a TypeError
Tuple Methods
While tuples are immutable, they have a few methods:
- count(x): Returns the number of occurrences of x in the tuple.
- index(x): Returns the index of the first occurrence of x in the tuple.
Use Cases for Tuples
- Storing fixed data that should not be changed.
- Returning multiple values from functions.
- Using as keys in dictionaries (since they are hashable).
- Efficiently accessing elements compared to lists.
Example
Python
coordinates = (3, 7)
print(coordinates.count(3)) # Output: 1
print(coordinates.index(7)) # Output: 1
In summary, tuples are used when you want to create an ordered collection of elements that should not be modified. They are often used for representing data that is considered constant or read-only.