Python Tuples
What is a Tuple in Python?
A tuple is an ordered, immutable collection of items. Tuples are defined using parentheses () and can store elements of different data types.
Tuple Syntax:
my_tuple = (item1, item2, item3)
You can also create a tuple without parentheses (optional):
my_tuple = 1, 2, 3
Example: Create a Tuple
person = ("Alice", 30, "Engineer")
print(person)
Output:
('Alice', 30, 'Engineer')
Tuple with One Element
For a single-element tuple, you must use a comma:
single = (5,)
print(type(single))
Output:
<class 'tuple'>
Without the comma, it's just an integer:
not_tuple = (5)
print(type(not_tuple))
Output:
<class 'int'>
Access Tuple Elements (Indexing & Slicing)
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
print(t[1:3]) # (20, 30)
Tuple is Immutable
You cannot modify a tuple after it's created.
t = (1, 2, 3)
# t[0] = 100 This will raise an error
Output:
TypeError: 'tuple' object does not support item assignment
Loop Through a Tuple
for item in t:
print(item)
Output:
1 2 3
Tuple Methods (Only Two)
1. count(value)
t = (1, 2, 2, 3, 2)
print(t.count(2)) # 3
2. index(value)
print(t.index(3)) # 3 (first occurrence)
Difference Between List and Tuple in Python
Feature | List | Tuple |
---|---|---|
Syntax | [1, 2, 3] | (1, 2, 3) |
Mutable | Yes | No (Immutable) |
Methods | Many | Only count(), index() |
Performance | Slower | Faster |
Use Case | Dynamic data | Fixed data |
When to Use Tuples?
- When the data should not be modified (immutability)
- As dictionary keys (since they are hashable)
- For performance optimization in large data sets
Nested Tuples
nested = (1, (2, 3), (4, 5))
print(nested[1][1]) # 3