Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Tuples and Tuple Methods

A tuple is an ordered, immutable sequence. Once created, its items cannot be added, removed or replaced. That makes tuples ideal for fixed records (coordinates, RGB colours, database rows), for returning several values from a function, and as dictionary keys or set members.

This lesson covers creating tuples, the single-item tuple gotcha, packing and unpacking, the two tuple methods count() and index(), named tuples, and how tuples differ from lists.

Why it matters

Tuples are how Python returns several values from a function, how it swaps variables, and what enumerate, zip and dict.items() give you. You use them constantly, often without writing the parentheses, and unpacking them is one of the most convenient features of the language.

Creating Tuples

Tuples are written with commas, usually in parentheses: (3, 4). The comma makes the tuple, not the parentheses — so a single-item tuple needs a trailing comma: ("x",). () is the empty tuple and tuple(iterable) converts other sequences.

Packing, Unpacking and Swapping

point = 3, 4 packs values into a tuple; x, y = point unpacks them. The star collects the rest: first, *rest = scores. Functions return multiple values as a tuple. Swapping two variables is simply a, b = b, a.

Tuple Methods and Operations

Tuples have just two methods: count(x) and index(x). They support indexing, slicing, len(), in, concatenation with +, repetition with *, and comparison (item by item). A tuple is immutable, but if it contains a mutable object such as a list, that inner list can still change.

Why Use Tuples

Tuples signal "this data should not change", protect against accidental modification, use slightly less memory than lists, and are hashable (if their items are), so they can be dictionary keys: distances[("Pune", "Mumbai")] = 150. For records with named fields, use collections.namedtuple or typing.NamedTuple.

Examples

Creating tuples and the single-item gotcha

Python
point = (3, 4)
colors = "red", "green", "blue"
single = ("python",)
not_a_tuple = ("python")
print(type(point), type(colors), type(single), type(not_a_tuple))
print(tuple([1, 2, 3]), tuple("abc"), ())
Output
<class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'str'>
(1, 2, 3) ('a', 'b', 'c') ()

Unpacking, star unpacking, swapping and multiple return values

Python
def min_max_avg(values):
    return min(values), max(values), sum(values) / len(values)

low, high, avg = min_max_avg([72, 88, 95, 61])
print(low, high, avg)

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

a, b = 10, 20
a, b = b, a
print(a, b)

for name, (lat, lon) in [("Pune", (18.52, 73.86)), ("Delhi", (28.61, 77.21))]:
    print(f"{name}: {lat}, {lon}")
Output
61 95 79.0
1 [2, 3, 4] 5
20 10
Pune: 18.52, 73.86
Delhi: 28.61, 77.21

count(), index(), operations and immutability

Python
t = (1, 2, 3, 2, 2, 4)
print(t.count(2), t.index(3), t[1:4], len(t), 4 in t)
print((1, 2) + (3,), ("ab",) * 3, (1, 2, 3) < (1, 3))

try:
    t[0] = 100
except TypeError as e:
    print("TypeError:", e)

record = ("Asha", [90, 85])
record[1].append(99)          # the inner list is still mutable
print(record)

distances = {("Pune", "Mumbai"): 150}
print(distances[("Pune", "Mumbai")])
Output
3 2 (2, 3, 2) 6 True
(1, 2, 3) ('ab', 'ab', 'ab') True
TypeError: 'tuple' object does not support item assignment
('Asha', [90, 85, 99])
150

Named tuples for readable records

Python
from collections import namedtuple
from typing import NamedTuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p, p.x, p[1], p._asdict())

class Student(NamedTuple):
    name: str
    score: int = 0

s = Student("Ravi", 88)
print(s, s.name, s._replace(score=92))
Output
Point(x=3, y=4) 3 4 {'x': 3, 'y': 4}
Student(name='Ravi', score=88) Ravi Student(name='Ravi', score=92)

Common Mistakes

  • Writing ("item") for a one-item tuple — it is just a string; add a trailing comma.
  • Trying to append to or modify a tuple.
  • Assuming a tuple containing a list is fully immutable.
  • Using tuples for records with many fields accessed by index instead of namedtuple/NamedTuple.

Exercise

Write a function that returns the smallest and the largest value of a list as a tuple, and unpack the result into two variables. Then use star unpacking to separate the first item of a list from the rest.

Expected output: 1 9 then [2, 3, 4]

Python · starter code
def min_max(values):
    # TODO: return the smallest and the largest value
    pass


# TODO: unpack the result for [4, 1, 9, 3] into two variables and print them

numbers = [1, 2, 3, 4]
# TODO: unpack numbers into "first" and a list "rest", and print rest
Show hints
  • Returning two values separated by a comma returns a tuple: return min(values), max(values).
  • A starred name collects the remaining items: first, *rest = numbers.
Show solution
Python · solution
def min_max(values):
    return min(values), max(values)


smallest, largest = min_max([4, 1, 9, 3])
print(smallest, largest)

numbers = [1, 2, 3, 4]
first, *rest = numbers
print(rest)

Quick quiz

1. What is the type of (5)?

  • A. tuple
  • B. list
  • C. int
  • D. It is a syntax error
Show answer

C. Parentheses alone do not make a tuple. A one-item tuple needs a trailing comma: (5,).

2. Which methods does a tuple have?

  • A. append and remove
  • B. add and discard
  • C. sort and reverse
  • D. count and index
Show answer

D. A tuple cannot be changed, so it has only the two methods that read from it.

3. Given t = (1, [2, 3]), what does t[1].append(4) do?

  • A. Changes the inner list, so t is (1, [2, 3, 4])
  • B. Raises TypeError
  • C. Creates a new tuple
  • D. Nothing
Show answer

A. The tuple cannot be made to hold a different object, but a mutable object inside it can still change.

Interview questions

Why use a tuple when a list can do everything a tuple can?

Show answer

A tuple cannot be modified, which protects data that should stay fixed and makes the intent clear. Because it is immutable it is hashable, provided its elements are, so it can be a dictionary key or a set element, which a list cannot. Tuples also use slightly less memory than lists.

What is a namedtuple?

Show answer

collections.namedtuple creates a tuple type whose positions also have names, so a point can be read as p.x and p.y as well as p[0] and p[1]. It is as light as an ordinary tuple and immutable, and makes code that handles records easier to read. typing.NamedTuple is the class-based form with type hints.

Key Points to Remember

  • Tuples are ordered and immutable; the comma creates them.
  • Packing/unpacking, star unpacking and swaps make tuples convenient.
  • Only two methods: count() and index().
  • Hashable tuples can be dict keys and set members.
  • namedtuple / NamedTuple add field names to tuples.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering