0%

11- Tuples in Python

A tuple is a list that cannot change. Immutable. Reliable. Perfect for fixed data like coordinates, dates, or configuration settings.

You know what a list is. A collection of items you can change, add to, and remove from. But sometimes you do not want changes. Sometimes you want a collection that stays exactly as you created it. Forever. This is a tuple. A tuple is like a list frozen in time. You create it. You access its items. You loop through it. But you cannot modify it. No appending. No inserting. No deleting. What you write is what you get. Tuples are used for data that should never change: days of the week, coordinates of a point, RGB color values, database records, and function return values.

🕯️ Magic Note

The word “tuple” comes from mathematical terms like “quintuple” (five), “sextuple” (six), “n-tuple” (any number). A tuple is simply a fixed-length sequence. Python tuples are immutable, which makes them faster than lists and safe to use as dictionary keys.

Creating Tuples
Use parentheses () to create a tuple. Separate items with commas. You can also create a tuple without parentheses (just commas).

Python

# Empty tuple

empty = ()

# Tuple with parentheses

colors = (“red”, “green”, “blue”)

# Tuple without parentheses (tuple packing)

coordinates = 10, 20, 30

print(coordinates) # (10, 20, 30)

# Single item tuple (needs a trailing comma)

single = (5,)

not_a_tuple = (5) # This is just the integer 5, not a tuple

# Mixed types

mixed = (42, “hello”, 3.14, True)

# Nested tuples

nested = ((1, 2), (3, 4), (5, 6))

# Using the tuple() constructor

from_list = tuple([1, 2, 3]) # (1, 2, 3)

from_string = tuple(“abc”) # (‘a’, ‘b’, ‘c’)

⚠️ To create a tuple with one item, you must add a trailing comma. (5,) is a tuple. (5) is just the number 5. This is one of the most common tuple mistakes.
Accessing Items by Index
Like lists and strings, tuples use zero-based indexing. You can access items using square brackets.

Python

colors = (“red”, “green”, “blue”, “yellow”, “purple”)

# Index: 0 1 2 3 4

# Negative: -5 -4 -3 -2 -1

print(colors[0]) # red

print(colors[2]) # blue

print(colors[-1]) # purple (last item)

print(colors[-2]) # yellow (second last)

Tuple Slicing
Slicing works exactly like with lists and strings. It returns a new tuple.

Python

numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

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

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

print(numbers[6:]) # (6, 7, 8, 9)

print(numbers[::2]) # (0, 2, 4, 6, 8)

print(numbers[::-1]) # (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

Tuples Are Immutable (Cannot Change)
This is the defining feature of tuples. Once created, a tuple cannot be modified. No adding. No removing. No changing items.

Python

colors = (“red”, “green”, “blue”)

# This causes an error

# colors[0] = “yellow” # TypeError: ‘tuple’ object does not support item assignment

# This causes an error

# colors.append(“yellow”) # AttributeError: ‘tuple’ object has no attribute ‘append’

# You cannot remove items either

# del colors[0] # TypeError: ‘tuple’ object doesn’t support item deletion

🕯️ Magic Note

Immutability is a feature, not a limitation. Because tuples cannot change, Python can optimize them. Tuples use less memory than lists and are slightly faster. They are also safe to use as dictionary keys (lists cannot be keys because they are mutable).

Tuple Methods
Tuples have only two methods because they cannot be modified: .count() and .index().

Python

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

# .count() counts occurrences of a value

print(numbers.count(2)) # 4 (2 appears four times)

print(numbers.count(9)) # 0

# .index() finds the first occurrence

print(numbers.index(3)) # 3 (first 3 is at index 3)

print(numbers.index(2)) # 1 (first 2 is at index 1)

# .index() with start and end parameters

print(numbers.index(2, 2)) # 2 (search from index 2)

# .index() raises ValueError if not found

# numbers.index(9) # ValueError: tuple.index(x): x not in tuple

Tuple Length and Membership
Use len() for length and in to check membership, just like lists.

Python

coordinates = (10, 20, 30)

print(len(coordinates)) # 3

print(10 in coordinates) # True

print(99 in coordinates) # False

print(10 not in coordinates) # False

print(99 not in coordinates) # True

# Empty tuple is falsy

empty = ()

if empty:

print(“This won’t print”)

else:

print(“Empty tuple is falsy”)

Looping Through Tuples
Tuples are iterable. You can loop through them just like lists.

Python

colors = (“red”, “green”, “blue”)

# Basic loop

for color in colors:

print(color)

# red

# green

# blue

# Loop with index using enumerate

for i, color in enumerate(colors):

print(f”{i}: {color}”)

# 0: red

# 1: green

# 2: blue

Tuple Packing and Unpacking
This is where tuples shine. Packing puts multiple values into a tuple. Unpacking extracts them into variables. This is one of Python’s most elegant features.

Python

# Tuple packing (comma creates a tuple)

point = 10, 20

print(point) # (10, 20)

# Tuple unpacking

x, y = point

print(x) # 10

print(y) # 20

# Multiple assignment (uses tuple unpacking)

a, b, c = 1, 2, 3

print(a, b, c) # 1 2 3

# Swapping variables (tuple unpacking magic)

x = 5

y = 10

x, y = y, x

print(x, y) # 10 5

# Unpacking with star (*) for remaining items

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

first, *rest = numbers

print(first) # 1

print(rest) # [2, 3, 4, 5] (rest becomes a list)

🕯️ Magic Note

Tuple unpacking is everywhere in Python. The multiple assignment a, b = 1, 2 is actually tuple packing and unpacking. The swap x, y = y, x uses tuple unpacking. This is elegant, readable, and very Pythonic.

Tuples as Dictionary Keys
Because tuples are immutable, they can be used as dictionary keys. Lists cannot. This is extremely useful for composite keys.

Python

# Tuple as a dictionary key (valid)

coordinates = {

(0, 0): “origin”,

(1, 0): “right”,

(0, 1): “up”,

(1, 1): “diagonal”

}

print(coordinates[(1, 0)]) # right

# List as a dictionary key (invalid)

# invalid = {[1, 2]: “list”} # TypeError: unhashable type: ‘list’

# Tuple with mutable items is also invalid

# invalid = {([1, 2], 3): “nested_list”} # TypeError: unhashable type: ‘list’

⚠️ A tuple containing a list is still mutable (because the list inside can change). Such a tuple cannot be used as a dictionary key. All items inside the tuple must be immutable for the tuple to be hashable.
Converting Between Lists and Tuples
Use list() to convert a tuple to a list. Use tuple() to convert a list to a tuple.

Python

# Tuple to list (becomes mutable)

colors_tuple = (“red”, “green”, “blue”)

colors_list = list(colors_tuple)

colors_list.append(“yellow”)

print(colors_list) # [‘red’, ‘green’, ‘blue’, ‘yellow’]

# List to tuple (becomes immutable)

numbers_list = [1, 2, 3]

numbers_tuple = tuple(numbers_list)

print(numbers_tuple) # (1, 2, 3)

# numbers_tuple.append(4) # Error! Tuples cannot be changed

Tuples vs Lists When to Use Which
Use a Tuple When...Use a List When...
Data should never changeData needs to change (add, remove, modify)
You need a dictionary keyYou do not need dictionary keys
You are returning multiple values from a functionYou need to collect items dynamically
The data has fixed meaning (RGB, coordinates, dates)The data is a collection of similar items
You want better performance and less memoryYou need flexibility over speed

Python

# Good tuple examples (fixed, meaningful data)

rgb = (255, 128, 0)

coordinates = (40.7128, -74.0060)

days = (“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”)

# Good list examples (dynamic collections)

scores = [95, 87, 92, 88, 96]

tasks = [“write code”, “test”, “deploy”]

shopping_cart = [“apple”, “bread”, “milk”]

Common Mistakes with Tuples
  • Forgetting the comma for single-item tuples: (5) is not a tuple, (5,) is
  • Trying to modify a tuple: my_tuple[0] = 10 causes TypeError
  • Using a tuple with mutable items as a dictionary key (unhashable)
  • Confusing tuple unpacking with list indexing
  • Calling .append() or .remove() on a tuple
  • Expecting a tuple to be mutable when it is not
Check Your Understanding
  • How do you create a tuple with a single item containing the number 42?
  • What happens if you try to change an item in a tuple?
  • Write code that swaps the values of a and b using tuple unpacking.
  • Why can a tuple be used as a dictionary key but a list cannot?
  • How do you convert a list named my_list into a tuple?
  • What is the output of len((1, 2, 3, 2, 1))?

⚡ Whisper

A tuple is a promise. You write the items once, in a specific order, and they stay exactly that way forever. No one can add to it. No one can remove from it. No one can rearrange it. This is not weakness. This is trust. When you pass a tuple to another part of your program, you know it will not be changed behind your back. When you use a tuple as a dictionary key, you know it will always find the same value. A tuple says: “Here is my truth. It does not change.” In a world of mutable lists, be a tuple. Be reliable. Be steady.

Related posts