A Tuple is a collection used to store multiple items in a single variable. Tuples are ordered, unchangeable (immutable), and allow duplicate values.
Creating a Tuple
fruits = ("apple", "banana", "mango")
print(fruits)
Output:
('apple', 'banana', 'mango')
Access Tuple Items
fruits = ("apple", "banana", "mango")
print(fruits[0])
print(fruits[1])
Output:
apple
banana
Negative Indexing
fruits = ("apple", "banana", "mango")
print(fruits[-1])
Output:
mango
Tuple Length
fruits = ("apple", "banana", "mango")
print(len(fruits))
Output:
3
Tuple with Different Data Types
data = ("Python", 25, True, 5.6)
print(data)
Output:
('Python', 25, True, 5.6)
Single Item Tuple
Always add a comma after the item.
fruit = ("apple",)
print(type(fruit))
Output:
<class 'tuple'>
Without comma:
fruit = ("apple")
print(type(fruit))
Output:
<class 'str'>
Loop Through a Tuple
fruits = ("apple", "banana", "mango")
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Check if Item Exists
fruits = ("apple", "banana", "mango")
if "banana" in fruits:
print("Found")
Output:
Found
Tuple Slicing
fruits = ("apple", "banana", "mango", "orange")
print(fruits[1:3])
Output:
('banana', 'mango')
Convert Tuple to List
Since tuples are immutable, convert them to a list before modifying.
fruits = ("apple", "banana", "mango")
fruit_list = list(fruits)
fruit_list.append("orange")
fruits = tuple(fruit_list)
print(fruits)
Output:
('apple', 'banana', 'mango', 'orange')
Key Points
- Tuples are ordered collections.
- Tuples cannot be modified after creation.
- Duplicate values are allowed.
- Faster than lists for fixed data.
- Use parentheses
()to create tuples.
Practice Exercise
Create a tuple containing 5 city names and print:
- First city
- Last city
- Total number of cities
- All cities using a loop