Tuples in Python are used to store multiple values in a single variable, similar to lists. However, unlike lists, tuples are ordered and immutable, meaning their values cannot be changed after creation.
Tuples are written using parentheses ().
Why Tuples Are Important
Tuples are useful when:
- Data should not be modified
- You need faster access than lists
- Ensuring data integrity
- Using values as dictionary keys
Example:
coordinates = (10, 20)
Creating a Tuple in Python
numbers = (1, 2, 3)
names = ("Aman", "Neha", "Ravi")
mixed = (1, "Python", True)
Tuple with One Item
To create a tuple with a single item, include a comma.
single = (5,)
Accessing Tuple Items
print(names[0])
print(names[-1])
Indexing works the same as lists.
Looping Through a Tuple
for name in names:
print(name)
Immutability of Tuples
Once a tuple is created, its values cannot be changed.
numbers[0] = 10 # Error
Tuple Methods
Tuples have limited methods.
| Method | Description |
|---|---|
| count() | Returns number of occurrences |
| index() | Returns index of value |
Example:
numbers = (1, 2, 2, 3)
print(numbers.count(2))
Tuple Packing and Unpacking
data = (10, 20, 30)
a, b, c = data
Tuple vs List
| Tuple | List |
|---|---|
| Immutable | Mutable |
| Faster | Slightly slower |
| Uses () | Uses [] |
Conclusion
Tuples are ideal when you want to store fixed data that should not change. They improve performance and protect data integrity in Python programs.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/