Python - Tuple
What are Tuples?
A tuple is a collection of ordered and immutable elements in Python. Tuples are similar to lists, but unlike lists, they cannot be changed (i.e., they are immutable).
Why Tuples?
- Immutability ensures data integrity.
- Faster than lists due to their fixed size.
- Used as keys in dictionaries because they are hashable.
- Preferred for fixed-size data, like coordinates (x, y).
How to Define Tuples
python
# Creating tuples empty_tuple = () single_item = (42,) fruits = ('apple', 'banana', 'cherry') mixed = (1, 2.5, 'hello')
Accessing Tuple Elements
Tuples support indexing and slicing, just like lists.
python
fruits = ('apple', 'banana', 'cherry') print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry print(fruits[1:]) # Output: ('banana', 'cherry')
Tuple Unpacking
python
point = (10, 20) x, y = point print(x) # 10 print(y) # 20
Tuple Methods
Tuples support a limited set of methods:
count()- Returns the number of times a value appearsindex()- Returns the first index of a value
python
nums = (1, 2, 2, 3) print(nums.count(2)) # 2 print(nums.index(3)) # 3
When to Use Tuples?
- When you want to ensure data cannot be changed.
- For returning multiple values from functions.
- To use fixed keys in a dictionary.
Pros
- Immutable — safer and reliable.
- Faster than lists.
- Can be used as dictionary keys.
Cons
- Cannot be modified after creation.
- Fewer built-in methods compared to lists.