Python Tutorial menu

Python Tuples

A tuple is like a list, but once it is created it cannot be changed.

Creating a Tuple

Write the items inside round brackets ():

Example

python
location = (24.86, 67.00)
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(location)
print(days[0])
print(len(days))
Output
(24.86, 67.0)
Mon
5

Tuples are ordered, unchangeable (immutable), and allow duplicates.

A Tuple With One Item

To make a tuple with only one item, you must add a comma. Without it, Python sees just a value in brackets.

Example

python
a = ("Karachi",)
b = ("Karachi")
print(type(a))
print(type(b))
Output
<class 'tuple'>
<class 'str'>

Reading Items

Indexing and slicing work the same way as with lists:

Example

python
colors = ("red", "green", "blue", "yellow")
print(colors[1])
print(colors[-1])
print(colors[1:3])
print("blue" in colors)
Output
green
yellow
('green', 'blue')
True

Tuples Cannot Change

Example

python
colors = ("red", "green", "blue")
colors[0] = "black"
Output
TypeError: 'tuple' object does not support item assignment

If you really need to change it, convert it to a list, change the list, and convert it back:

Example

python
colors = ("red", "green", "blue")
temp = list(colors)
temp[0] = "black"
colors = tuple(temp)
print(colors)
Output
('black', 'green', 'blue')

Unpacking a Tuple

You can take the values out of a tuple into separate variables in one line. This is called unpacking:

Example

python
student = ("Ayesha", 20, "BSCS")
name, age, program = student
print(name)
print(age)
print(program)
Output
Ayesha
20
BSCS

Use * to collect the remaining items into a list:

Example

python
scores = (95, 88, 76, 64, 50)
top, *others = scores
print(top)
print(others)
Output
95
[88, 76, 64, 50]

Tuple Methods

Tuples have only two methods:

MethodWhat it does
count(x)How many times x appears
index(x)Position of the first x

List or Tuple?

Use a list whenUse a tuple when
Items will be added or removedThe data should stay fixed
Example: a shopping cartExample: GPS coordinates, days of the week

Tuples are a little faster than lists and protect your data from accidental changes. A function that returns several values actually returns a tuple.

Exercise

Exercise

How do you create a tuple with one item, "pen"?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp