Tuples
A tuple in Python is a collection that is ordered and unchangeable (also called immutable).
It's very similar to a list, but once a tuple is created, you cannot modify its elements.
How to Create a Tuple:
Even if a tuple has only one item, you must include a comma:
single_item_tuple = (42,) # ← Notice the comma
Without the comma, Python will treat it as just a number.
Key Features of Tuples:
1. Immutability - Cannot be changed.
Once a tuple is created, you cannot modify, add, or remove elements.
# Creating a tuple
tup = (11, 22, 33, 44)
# Trying to change the third element
tup[2] = 59
#Output - Error: 'tuple' object does not support item assignment
2. Ordered Collection - Elements have fixed positions.
Elements in a tuple maintain their order and can be accessed by index.
# Example
animals = ("cat", "dog", "bird", "fish")
# Access items by position
first_animal = animals[0] # "cat"
second_animal = animals[1] # "dog"
last_animal = animals[-1] # "fish" (negative means from end)
print("First animal:", first_animal)
print("Last animal:", last_animal)
3. Allows Duplicate Values.
Tuples can contain multiple instances of the same value.
# Example
grades = (85, 90, 85, 78, 90, 85)
print("All grades:", grades)
print("How many 85s:", grades.count(85)) # Output: 3
4. Multiple Data Types.
Tuples can store different types of data in a single collection.
# Example
mixed_tuple = (42, "Hello", 3.14, True)
print("Mixed tuple:", mixed_tuple)
5. Tuple Packing and Unpacking.
You can pack multiple values into a tuple and unpack them into separate variables.
# Different ways to create tuples
way1 = (1, 2, 3) # With parentheses
way2 = 1, 2, 3 # Without parentheses
way3 = (10,) # Single item (comma needed!)
print("Way 1:", way1)
print("Way 2:", way2)
print("Way 3:", way3)
6. Slicing - Extract Portions of Tuple.
You can extract a portion of a tuple using slicing.
# Example: Weekly Temperature Data
temperatures = (22, 25, 28, 30, 27, 24, 21)
# Slicing syntax: tuple[start:end:step]
weekdays = temperatures[0:5] # First 5 days
weekend = temperatures[5:7] # Last 2 days
every_other_day = temperatures[::2] # Every alternate day
print(f"Weekday temps: {weekdays}") # (22, 25, 28, 30, 27)
print(f"Weekend temps: {weekend}") # (24, 21)
print(f"Alternate days: {every_other_day}") # (22, 28, 27, 21)
7. Loop Through Tuple
# Example
fruits = ("apple", "banana", "cherry")
# Looping through the tuple
for fruit in fruits:
print("Fruit:", fruit)
Simple Examples:
Example 1: Store Coordinates
# Store x, y position
my_position = (10, 20)
x = my_position[0] # 10
y = my_position[1] # 20
print(f"I am at position ({x}, {y})")
Example 2: Store Person Information
person = ("Alice", 25, "Teacher")
name = person[0]
age = person[1]
job = person[2]
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Job: {job}")
Example 3: Store Multiple Values
# Test scores
scores = (85, 92, 78, 96, 88)
print("All scores:", scores)
print("Highest score:", max(scores))
print("Lowest score:", min(scores))
print("Total scores:", len(scores))
Example 4: Compare Tuples
score1 = (85, 90)
score2 = (85, 88)
print("Score1 > Score2:", score1 > score2) # True
print("Scores are same:", score1 == score2) # False
Simple Tricks
Swap Two Variables.
a = 10
b = 20
a,b = b,a
print("a:",a,"b:",b)
Unpack Tuple Values
student_info = ("Bob", 18, 95)
# Get all values at once
name, age, marks = student_info
print("Student name:", name)
print("Student age:", age)
print("Student marks:", marks)