Tuples
Learn what tuples are, how they differ from lists, and when to use them in Python.
Tuples
A tuple is an ordered collection of items — just like a list. The one big difference is that tuples are immutable. Once you create a tuple, you cannot change it. You cannot add items, remove items, or modify existing ones.
coordinates = (40.7128, 74.0060)
rgb = (255, 128, 0)
person = ("Ali", 22, "Lahore")If a list is a whiteboard you can erase and rewrite, a tuple is something carved in stone — it stays exactly as it was created.
Creating a tuple
Use parentheses with comma-separated values:
# empty tuple
empty = ()
# tuple with values
fruits = ("apple", "banana", "mango")
# mixed types
profile = ("Ali", 22, True)
# tuple from a list
numbers = tuple([1, 2, 3, 4, 5])
print(numbers) # (1, 2, 3, 4, 5)A tuple with one item needs a trailing comma — otherwise Python treats the parentheses as just grouping, not a tuple:
not_a_tuple = ("apple")
print(type(not_a_tuple)) # <class 'str'> — just a string in parentheses
real_tuple = ("apple",)
print(type(real_tuple)) # <class 'tuple'>The trailing comma is easy to forget. ("apple") is a string. ("apple",) is a tuple. The comma is what makes it a tuple, not the parentheses.
Parentheses are optional
Python actually identifies a tuple by the commas, not the parentheses. These are all valid tuples:
person = "Ali", 22, "Lahore"
print(person) # ('Ali', 22, 'Lahore')
print(type(person)) # <class 'tuple'>The parentheses are just there for readability. You will see this most in function returns:
def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple
result = min_max([3, 1, 4, 1, 5, 9])
print(result) # (1, 9)Accessing items
Exactly the same as lists — indexing and slicing both work:
person = ("Ali", 22, "Lahore")
print(person[0]) # Ali
print(person[-1]) # Lahore
print(person[0:2]) # ('Ali', 22)What does not work — changing an item:
person[0] = "Sara" # TypeError: 'tuple' object does not support item assignmentUnpacking — the real power of tuples
Unpacking means pulling the values out of a tuple and assigning them to separate variables in one line:
person = ("Ali", 22, "Lahore")
name, age, city = person
print(name) # Ali
print(age) # 22
print(city) # LahoreThe number of variables on the left must match the number of items in the tuple:
name, age = person # ValueError: too many values to unpackIgnoring values with _
If you only want some values, use _ for the ones you do not care about:
person = ("Ali", 22, "Lahore")
name, _, city = person # ignore the age
print(name) # Ali
print(city) # LahoreCollecting the rest with *
Use * to collect multiple remaining values into a list:
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
*beginning, last = (1, 2, 3, 4, 5)
print(beginning) # [1, 2, 3, 4]
print(last) # 5
first, *middle, last = (1, 2, 3, 4, 5)
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5Swapping variables
Tuple unpacking makes swapping two variables clean and simple — no temporary variable needed:
a = 10
b = 20
a, b = b, a
print(a) # 20
print(b) # 10Python creates a tuple (b, a) on the right side first, then unpacks it into a and b.
Tuple methods
Because tuples are immutable, they only have two methods:
count() — count occurrences
numbers = (1, 2, 3, 2, 4, 2, 5)
print(numbers.count(2)) # 3
print(numbers.count(9)) # 0index() — find the position
fruits = ("apple", "banana", "mango")
print(fruits.index("banana")) # 1Tuple vs List — when to use which
| List | Tuple | |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutable | Yes | No |
| Methods | Many | Only count and index |
| Speed | Slightly slower | Slightly faster |
| Use for | Collections that change | Fixed data |
Use a tuple when:
- The data should not change — coordinates, RGB values, database records
- You are returning multiple values from a function
- You want to use the collection as a dictionary key (lists cannot be dictionary keys — tuples can)
- You want to signal to other developers — this data is fixed, do not modify it
Use a list when:
- You need to add, remove, or change items
- The collection grows or shrinks over time
# Good use of tuple — these values never change
SCREEN_SIZE = (1920, 1080)
DB_CONFIG = ("localhost", 5432, "mydb")
DIRECTIONS = ("north", "south", "east", "west")
# Good use of list — this changes as users are added
active_users = ["ali", "sara"]
active_users.append("omar")Tuples as dictionary keys
Lists cannot be used as dictionary keys because they are mutable. Tuples can:
# Using tuples as keys — coordinates mapped to a location name
locations = {
(40.7128, 74.0060): "New York",
(51.5074, 0.1278): "London",
(31.5497, 74.3436): "Lahore",
}
print(locations[(40.7128, 74.0060)]) # New YorkNamed tuples — tuples with labels
A regular tuple uses index numbers to access values — not very readable:
person = ("Ali", 22, "Lahore")
print(person[0]) # what is index 0 again?Python's collections module gives you namedtuple — a tuple where each position has a name:
from collections import namedtuple
Person = namedtuple("Person", ["name", "age", "city"])
ali = Person(name="Ali", age=22, city="Lahore")
print(ali.name) # Ali
print(ali.age) # 22
print(ali.city) # Lahore
# Still works like a normal tuple
print(ali[0]) # Ali
print(len(ali)) # 3Named tuples are still immutable — you get the clarity of names with the safety of tuples.
If you find yourself using named tuples a lot, look into dataclasses — covered in the OOP section. They are more powerful and flexible for the same use case.
A real example
A function that returns student results as a tuple:
def analyze_scores(scores):
return min(scores), max(scores), sum(scores) / len(scores)
scores = [88, 92, 79, 95, 84, 76]
lowest, highest, average = analyze_scores(scores)
print(f"Lowest: {lowest}")
print(f"Highest: {highest}")
print(f"Average: {average:.1f}")Output:
Lowest: 76
Highest: 95
Average: 85.7Summary
| Concept | Example |
|---|---|
| Create a tuple | t = (1, 2, 3) |
| Single item tuple | t = (1,) |
| Access item | t[0] |
| Unpack | a, b, c = t |
| Ignore a value | a, _, c = t |
| Collect the rest | first, *rest = t |
| Swap variables | a, b = b, a |
| Count occurrences | t.count(x) |
| Find position | t.index(x) |