Python Mastery – From Basics to Brilliance / Data Structures in Python

Tuples

A tuple is an ordered, immutable (unchangeable) collection of items. Once created, its values cannot be altered.

coordinates = (10.5, 20.3)

πŸ” Why Use Tuples?

  • You want to protect data from being modified.

  • Useful for fixed collections, like dates, coordinates, RGB values, etc.

  • Faster and more memory-efficient than lists.


πŸ“Œ Tuple Characteristics

t = (1, 2, 3)
print(t[1])      # βœ… Accessing second element β†’ 2

# t[0] = 10      # ❌ TypeError: 'tuple' object does not support item assignment
  • βœ… Indexed (like lists)

  • ❌ Cannot be changed

  • βœ… Can contain mixed data types


πŸ” Looping Through a Tuple

for value in t:
    print(value)
1
2
3

πŸ“¦ Tuple with One Element?

You need a comma to define a single-element tuple:

x = (5)      # This is just an int
y = (5,)     # βœ… This is a tuple

🧠 Tuple vs List

Feature

List ([])

Tuple (())

Mutable

βœ… Yes

❌ No

Speed

Slower

Faster

Use case

Changing data

Fixed data


πŸ’‘ Real-life Analogy

A tuple is like a passport record β€” once issued, you can’t change the name, date of birth, etc.

A list is like a shopping list β€” you can add, remove, or reorder items anytime.


✨ Bonus: Tuple Unpacking

name, age = ("Alice", 30)
print(name)  # Alice
print(age)   # 30