In Python, a tuple is an immutable sequence of items, meaning once created, its elements cannot be changed. Tuples are often used to group related data.
Creating a Tuple
You can create a tuple by placing elements inside parentheses ()
, separated by commas.
# Creating tuples empty_tuple = () # An empty tuple numbers = (1, 2, 3, 4, 5) # A tuple of integers mixed = (1, "hello", 3.14, True) # A tuple with mixed data types print(numbers) # Output: (1, 2, 3, 4, 5)
Accessing Tuple Elements
Like lists, you can access tuple elements using their index. Tuples are also zero-indexed.
# Accessing elements fruits = ("apple", "banana", "cherry") print(fruits[0]) # Output: apple print(fruits[2]) # Output: cherry
Tuple Immutability
Tuples are immutable, meaning you cannot change, add, or remove elements after the tuple is created.
# Attempting to modify a tuple fruits = ("apple", "banana", "cherry") # This will raise an error # fruits[1] = "blueberry" # TypeError: 'tuple' object does not support item assignment
Tuple Methods
Tuples have only two built-in methods: count()
and index()
.
1. count()
Returns the number of times a specified value appears in the tuple.
# Example of count() numbers = (1, 2, 2, 3, 4, 2) count_of_twos = numbers.count(2) print(count_of_twos) # Output: 3
2. index()
Returns the index of the first occurrence of a specified value.
# Example of index() fruits = ("apple", "banana", "cherry") position = fruits.index("banana") print(position) # Output: 1
Tuple Packing and Unpacking
Tuples allow packing multiple values into one variable and unpacking them into separate variables.
# Tuple packing person = ("John", 25, "Engineer") # Tuple unpacking name, age, profession = person print(name) # Output: John print(age) # Output: 25 print(profession) # Output: Engineer
Using Tuples as Dictionary Keys
Since tuples are immutable, they can be used as keys in dictionaries, unlike lists.
# Tuple as a dictionary key locations = { (40.7128, -74.0060): "New York", (34.0522, -118.2437): "Los Angeles" } print(locations[(40.7128, -74.0060)]) # Output: New York
When to Use Tuples
- When you want to ensure the data cannot be modified.
- When you need a lightweight alternative to lists for fixed data.
- When using as dictionary keys or ensuring data integrity.
Conclusion
Python tuples are an essential data structure that provides a way to store immutable, ordered collections of items. They are simple yet powerful, offering a lightweight solution for grouping related data.