Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Introduction to Tuples

10.1

Introduction to Tuples

A tuple is an ordered sequence that can hold elements of different data types — integers, floats, strings, lists, and even other tuples. The elements are written inside parentheses (round brackets) and separated by commas. Just like strings and lists, every element of a tuple sits at a fixed position, so individual elements can be accessed with index values starting from 0.

Creating tuples of different kinds

A tuple may contain elements that are all of one type, a mix of types, or even container types such as a list or another tuple as a single element:

# a tuple of integers
>>> marks = (78, 92, 65, 88, 71)
>>> marks
(78, 92, 65, 88, 71)

# a tuple mixing data types: strings, an int and a float
>>> report = ('Physics', 91, 'Chemistry', 84.5)
>>> report
('Physics', 91, 'Chemistry', 84.5)

# a tuple containing a list as one of its elements
>>> mixed = (5, 15, 25, [35, 45])
>>> mixed
(5, 15, 25, [35, 45])

# a tuple containing another tuple as an element
>>> nested = (1, 2, 3, (100, 200))
>>> nested
(1, 2, 3, (100, 200))

The single-element tuple needs a trailing comma

This is a classic trap. If a tuple is to contain only one element, that element must be followed by a comma. Writing the value in parentheses without the comma does not create a tuple at all — Python simply treats the parentheses as ordinary grouping, so the variable gets the plain value (for example an integer):

# WRONG way — no comma, so this is just the integer 20
>>> t = (20)
>>> t
20
>>> type(t)
<class 'int'>

# CORRECT way — the element is followed by a comma
>>> t = (20,)
>>> t
(20,)
>>> type(t)
<class 'tuple'>

A comma-separated sequence without parentheses is a tuple by default

If you write comma-separated values without any brackets at all, Python packs them into a tuple automatically:

>>> seq = 7, 8, 9      # no parentheses, only commas
>>> type(seq)
<class 'tuple'>
>>> print(seq)
(7, 8, 9)

When to prefer a tuple over a list

As a general convention, a list is used to store elements of the same data type, whereas a tuple is used to store elements of different data types (for example one student record: name, roll number, marks).

What this chapter covers

The chapter walks through: introduction to tuples → tuple operations → tuple methods and built-in functions → tuple assignment → nested tuples → tuple handling (programs) → introduction to dictionaries → dictionaries are mutable → dictionary operations → traversing a dictionary → dictionary methods and built-in functions → manipulating dictionaries.