LEARN COMPLETE PYTHON IN 24 HOURS

8. Tuples

Tuples are very similar to lists, but with one big difference: they are immutable (cannot be changed after creation).

8.1 What is a Tuple? Why Use It?

A tuple is an ordered, immutable collection of items. Defined using parentheses () (or sometimes without them).

Creating a tuple:

Python

# Empty tuple empty = () # Single item tuple (must have comma!) single = (5,) # Note the comma! wrong = (5) # This is just integer 5, not tuple # Multiple items coordinates = (10, 20, 30) person = ("Anshuman", 25, "Muzaffarpur", True) mixed = (1, "hello", 3.14, [10, 20]) # can contain lists (mutable inside)

Why Use Tuples?

  • Immutable → Data cannot be accidentally changed (safer for fixed data)

  • Faster than lists (because immutable)

  • Use as dictionary keys (lists cannot be keys because mutable)

  • Return multiple values from functions easily

  • Memory efficient for fixed collections

  • Common in real-world: coordinates, RGB colors, days of week, database records

Example – Fixed data

Python

days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") print(days[0]) # Monday # days[0] = "Sun" # Error! Tuples are immutable

8.2 Tuple vs List – Quick Comparison

FeatureTupleListSyntax(1, 2, 3) or 1, 2, 3[1, 2, 3]Mutable?No (cannot change)Yes (can add/remove/change)SpeedFaster (fixed size)Slightly slowerMemory usageLessMoreCan be dictionary key?YesNoMethods availableVery few (count, index)Many (append, pop, sort, etc.)Use when...Data should never changeData needs to be modifiedCommon examplesCoordinates, config valuesShopping list, to-do items

Quick Tip: If you don’t need to change the collection → use tuple (safer & faster). If you need to modify → use list.

8.3 Tuple Methods (count, index)

Tuples have only two methods because they are immutable.

  1. count(value) → Returns how many times a value appears

Python

numbers = (1, 2, 2, 3, 2, 4) print(numbers.count(2)) # 3 print(numbers.count(5)) # 0

  1. index(value) → Returns first position (index) of value (Raises ValueError if not found)

Python

colors = ("red", "green", "blue", "green") print(colors.index("green")) # 1 print(colors.index("blue")) # 2 # print(colors.index("yellow")) # Error: not in tuple

Tip: To check if item exists first:

Python

if "yellow" in colors: print(colors.index("yellow")) else: print("Not found")

8.4 Packing & Unpacking

Packing → Putting multiple values into a tuple automatically.

Unpacking → Extracting values from a tuple into variables.

Basic Packing & Unpacking

Python

# Packing person_info = "Anshuman", 25, "Muzaffarpur" # tuple created automatically # Unpacking name, age, city = person_info print(name) # Anshuman print(age) # 25 print(city) # Muzaffarpur

Unpacking with * (extended unpacking)

Python

numbers = (1, 2, 3, 4, 5) first, *middle, last = numbers print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5

Swap two variables (classic use of unpacking)

Python

a = 10 b = 20 a, b = b, a # No temporary variable needed! print(a, b) # 20 10

Return multiple values from function

Python

def get_person(): return "Anshuman", 25, "Bihar" # packs into tuple name, age, state = get_person() print(f"{name} is {age} from {state}")

Ignore values during unpacking

Python

data = (100, 200, 300, 400) x, , y, = data # _ means ignore print(x, y) # 100 300

Mini Project Example – Coordinate System

Python

def move(position, direction): x, y = position # unpack tuple if direction == "up": y += 10 elif direction == "down": y -= 10 elif direction == "left": x -= 10 elif direction == "right": x += 10 return (x, y) # pack and return new position current = (0, 0) print("Start:", current) current = move(current, "right") print("After right:", current) # (10, 0) current = move(current, "up") print("After up:", current) # (10, 10)

Output:

text

Start: (0, 0) After right: (10, 0) After up: (10, 10)

This completes the full Tuples section — short but very useful in real Python programming!