A Tuple in Python (programming language) is a collection used to store multiple items in a single variable, similar to a list.
However, tuples are immutable, which means their values cannot be changed after creation.
Key Characteristics
- Ordered
- Immutable (cannot modify items)
- Allows duplicate values
- Faster than lists for fixed data
1οΈβ£ Creating a Tuple
Tuples are created using parentheses ().
numbers = (1, 2, 3, 4, 5)
print(numbers)
Output
(1, 2, 3, 4, 5)
2οΈβ£ Tuple with Different Data Types
A tuple can store multiple data types.
data = (10, "Python", 3.14, True)
print(data)
Output
(10, 'Python', 3.14, True)
3οΈβ£ Accessing Tuple Elements
Items are accessed using index numbers starting from 0.
fruits = ("apple", "banana", "cherry")
print(fruits[0])
print(fruits[1])
print(fruits[2])
Output
apple
banana
cherry
Negative Indexing
print(fruits[-1])
Output
cherry
4οΈβ£ Tuple Length
Use len() to find the number of items in a tuple.
fruits = ("apple", "banana", "cherry")
print(len(fruits))
Output
3
5οΈβ£ Tuple with One Item
A comma is required when creating a single-item tuple.
single = ("apple",)
print(type(single))
Output
<class 'tuple'>
Without the comma, Python treats it as a string.
6οΈβ£ Loop Through a Tuple
You can loop through tuple items using a for loop.
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
7οΈβ£ Tuple Slicing
You can extract a range of items from a tuple.
numbers = (1, 2, 3, 4, 5)
print(numbers[1:4])
Output
(2, 3, 4)
8οΈβ£ Converting Tuple to List
Since tuples cannot be modified, convert them into a list to change values.
fruits = ("apple", "banana", "cherry")
temp = list(fruits)
temp[1] = "orange"
fruits = tuple(temp)
print(fruits)
Output
('apple', 'orange', 'cherry')
9οΈβ£ Joining Tuples
Two tuples can be combined using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result)
Output
(1, 2, 3, 4, 5, 6)
π Tuple Packing and Unpacking
Packing
data = ("apple", 10, True)
Unpacking
fruit, number, status = dataprint(fruit)
print(number)
print(status)
Output
apple
10
True
β Summary
| Feature | Tuple |
|---|---|
| Ordered | Yes |
| Mutable | No |
| Duplicates allowed | Yes |
| Syntax | ( ) |