Tuples in Python

A tuple is a collection of items that is ordered and immutable. Once created, a tuple cannot be changed.

💡 Tuples are written using round brackets ( ).

Creating a Tuple

numbers = (1, 2, 3)
names = ("Khushi", "Python", "Learner")
single = (5,)

print(numbers)
print(names)
print(single)

Accessing Tuple Elements

Tuple elements are accessed using index positions, similar to lists.

colors = ("red", "green", "blue")

print(colors[0])
print(colors[1])
print(colors[-1])

Immutability of Tuples

Tuples cannot be modified after creation.

❌ This will cause an error:
colors = ("red", "green", "blue")
colors[1] = "yellow"   # TypeError

Tuple Unpacking

You can assign tuple values to multiple variables at once.

person = ("Khushi", 18, "India")
name, age, country = person

print(name)
print(age)
print(country)

Tuple Methods

Tuples have limited methods compared to lists.

nums = (1, 2, 2, 3)

print(nums.count(2))
print(nums.index(3))

When to Use Tuples?

  • When data should not change
  • For fixed collections
  • Better performance than lists

Practice Exercises

  1. Create a tuple of 5 subjects
  2. Print the first and last subject
  3. Unpack the tuple into variables