Tuples

A tuple is a collection data type in Python used to store multiple items in a single variable.
Tuples are ordered, immutable (unchangeable), and allow duplicate values.

Tuples are similar to lists, but the main difference is that tuples cannot be modified after creation.

CREATING A TUPLE

Tuples are created using round brackets ( ).

numbers = (1, 2, 3, 4, 5)

A tuple can contain different data types:

mixed = (10, "Python", 3.14, True)

SINGLE-ITEM TUPLE

To create a tuple with one item, you must add a comma.

single = (5,)

Without the comma, it is not considered a tuple.

ACCESSING TUPLE ELEMENTS

Indexing works the same as lists. Index starts from 0.

fruits = ("Apple", "Banana", "Mango")print(fruits[0])   # Apple
print(fruits[-1]) # Mango

SLICING A TUPLE

numbers = (1, 2, 3, 4, 5)
print(numbers[1:4]) # (2, 3, 4)

TUPLES ARE IMMUTABLE

You cannot change, add, or remove elements after creation.

fruits = ("Apple", "Banana", "Mango")
# fruits[1] = "Orange" # This will give an error

CONVERTING TUPLE TO LIST

If you need to modify a tuple, convert it into a list.

fruits = ("Apple", "Banana", "Mango")temp = list(fruits)
temp[1] = "Orange"
fruits = tuple(temp)print(fruits)

LOOPING THROUGH A TUPLE

numbers = (1, 2, 3)for num in numbers:
print(num)

COMMON TUPLE METHODS

Tuples have limited methods because they are immutable.

numbers = (1, 2, 3, 2, 4)print(numbers.count(2))   # Count occurrences
print(numbers.index(3)) # Find index

PACKING AND UNPACKING TUPLES

Packing

person = ("Hira", 25, "Pakistan")

Unpacking

name, age, country = person
print(name)
print(age)
print(country)

WHEN TO USE TUPLES

• When data should not change
• For fixed collections (coordinates, records, etc.)
• Faster than lists in some cases
• Can be used as dictionary keys (if containing immutable items)

IMPORTANT POINTS

• Tuples are ordered and indexed
• Tuples are immutable
• Allow duplicate values
• Use parentheses ( )

Understanding tuples helps you work with fixed and secure data in Python programs.

Home » PYTHON INTERMEDIATE (PYI) > Data Structures > Tuples