📦 Data Structures

Tuples

ट्यूपल

⏱ 2 hr2 topicsInteractive
🎯 By the end: You can create and use tuples, pack and unpack them, and explain when a tuple is a better choice than a list.

A tuple is like a list — an ordered collection — but with one crucial difference: it's immutable. Once you create a tuple, you can't change it. Tuples are written with round brackets: point = (4, 5). That 'you can't change it' rule is exactly why they're useful for data that shouldn't change.

1Creating and using tuples

Create a tuple with round brackets (or just commas). You index and slice it exactly like a list — but any attempt to change it fails:

colours = ("red", "green", "blue")
print(colours[0])      # red
print(len(colours))    # 3
# colours[0] = "pink"  # ERROR: tuples are immutable
One-item tuple gotcha: (5) is just the number 5 in brackets. To make a tuple of one item you need a trailing comma: (5,). This trips people up in exams.
Tuples are immutable▶ runs real Python
main.py
Output
Click Run to execute.
Key points
  • A tuple is an ordered, immutable collection, usually written with round brackets.
  • Index and slice it like a list, but you cannot change, add or remove items.
  • A one-item tuple needs a trailing comma: (5,), not (5).

2Packing, unpacking, and tuple vs list

A neat tuple feature is packing and unpacking. Several values can be packed into one tuple, and then unpacked into separate variables in a single line:

point = (10, 20)        # packing
x, y = point            # unpacking
print(x, y)             # 10 20

a, b = b, a             # a famous one-line swap!

Tuple or list — which to use?

ListTuple
Brackets[ ]( )
Mutable?Yes (can change)No (fixed)
SpeedSlightly slowerSlightly faster
Use forData that changesFixed data (coordinates, dates)
Choose a tuple when the data should never change — it's faster and safer (you can't accidentally modify it). Choose a list when you'll add, remove or update items.
Packing & unpacking▶ runs real Python
main.py
Output
Click Run to execute.
Key points
  • Packing puts values into a tuple; unpacking spreads a tuple into separate variables.
  • a, b = b, a swaps two variables in one line using tuples.
  • Use a tuple for fixed data (faster, safer); a list when items will change.

★ Practical: tuples in action

In the playground:

  1. Make a tuple holding a student's (name, age, class).
  2. Unpack it into three variables and print a sentence using them.
  3. Try to change one item and observe the error — then explain in a comment why it happened.
  4. Swap two variables in a single line using tuple assignment.

Ready for the chapter test?

Answer 5 questions. Score 60% or more to mark this chapter complete.

Start the test →

💡 Log in to save your progress and earn the certificate.