Skip to content

Module 8 · Python Data Structures — topic 11 of 22

Tuple operations

Everything you can do with tuples: indexing and slicing, concatenation and repetition, membership, unpacking with *, count() and index(), comparison and sorting, and converting between tuples and lists.

Beginner 10 min read·Lesson 114 of 306 in Python Programming

Learning objectives

  • Apply sequence operations to tuples
  • Unpack tuples including with starred names
  • Compare and sort tuples, and convert to and from lists

Definition

Everything you can do with tuples: indexing and slicing, concatenation and repetition, membership, unpacking with *, count() and index(), comparison and sorting, and converting between tuples and lists.

Introduction

Tuples support every sequence operation that doesn’t change the sequence. Combined with unpacking and comparison rules, these operations make tuples a powerful tool for working with records.

Why it matters

Sorting students by marks then name, unpacking returned values, building keys from several fields and converting data between list and tuple forms are routine tasks in real programs.

Detailed explanation

Indexing and slicing work as for lists and return items or new tuples.

+ concatenates two tuples into a new tuple; * repeats a tuple.

in tests membership; len(), min(), max() and sum() work on tuples of suitable values.

count(x) and index(x) are the only tuple methods.

Unpacking assigns items to names; a starred name collects the rest into a list: first, *middle, last = (1, 2, 3, 4).

Tuples compare item by item from the left: (85, "Ben") < (85, "Chen") is True because the marks tie and "Ben" < "Chen". This makes tuples convenient sort keys.

Convert with list(t) when you need to modify, and tuple(items) to freeze a list.

Syntax

Python
combined = t1 + t2
first, *rest = t
t.count(x)
t.index(x)
sorted(records, key=lambda r: (r[1], r[0]))
  • Operations return new tuples.
  • Starred unpacking collects the rest.
  • Tuples compare item by item.

Code examples

Sequence operations

Python
a = (1, 2, 3)
b = (4, 5)
print(a + b, a * 2)
print(a[1:], 2 in a, len(a + b))
print((1, 2, 2, 3).count(2), (1, 2, 3).index(3))
Output
(1, 2, 3, 4, 5) (1, 2, 3, 1, 2, 3)
(2, 3) True 5
2 2

Unpacking

Python
first, *middle, last = (10, 20, 30, 40, 50)
print(first, middle, last)
name, (city, pin) = ("Asha", ("Pune", 411001))
print(name, city, pin)
Output
10 [20, 30, 40] 50
Asha Pune 411001

More examples

Sorting records by several fields

Python
records = [("Ben", 85, 19), ("Asha", 91, 20), ("Chen", 85, 18), ("Dev", 91, 19)]
ranked = sorted(records, key=lambda r: (-r[1], r[0]))
for name, mark, age in ranked:
print(f"{name:<5}{mark:>4}{age:>4}")
print((85, "Ben") < (85, "Chen"))
frozen = tuple(sorted({"b", "a", "c"}))
print(frozen)
editing = list(frozen)
editing.append("d")
print(tuple(editing))
Output
Asha   91  20
Dev    91  19
Ben    85  19
Chen   85  18
True
('a', 'b', 'c')
('a', 'b', 'c', 'd')

Step-by-step explanation

  • The key (-mark, name) sorts by mark descending, then name ascending for ties.
  • Unpacking in the for loop gives each field a clear name.
  • Tuple comparison checks 85 against 85, then "Ben" against "Chen".
  • tuple() freezes a sorted set; list() thaws it for editing, and tuple() freezes the result again.

Expected output

Running “Sorting records by several fields” prints exactly:

TextOutput
Asha 91 20
Dev 91 19
Ben 85 19
Chen 85 18
True
('a', 'b', 'c')
('a', 'b', 'c', 'd')

Practical applications

  • Leaderboards sort by score and then by time using tuple keys.
  • Configuration constants are stored as tuples so they can’t be modified.
  • Database code unpacks row tuples into named variables.

Best practices

  • Use tuple keys to sort by several fields.
  • Unpack records into named variables for readability.
  • Convert to a list only when you truly need to modify the data.

Common mistakes

Unpacking the wrong number of items

Avoid

a, b = (1, 2, 3)

Prefer

a, b, c = (1, 2, 3) # or a, *b = ...

The number of names must match unless a starred name collects the extra items.

Sorting descending by negating text

Avoid

key=lambda r: (-r[0], r[1]) # r[0] is a name

Prefer

Sort numbers with -, or use reverse=True for the whole key.

Only numbers can be negated; strings raise TypeError.

Key takeaways

  • Tuples support indexing, slicing, +, *, in, count and index.
  • Unpacking (with *) splits tuples into names.
  • Tuples compare item by item, making them good sort keys.

Try it yourself

  1. 1
    Sort a list of (name, city) tuples by city, then by name.
  2. 2
    Unpack the first and last items of a 6-item tuple, collecting the rest in a list.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic