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
location = (24.86, 67.00)
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(location)
print(days[0])
print(len(days))(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
a = ("Karachi",)
b = ("Karachi")
print(type(a))
print(type(b))<class 'tuple'> <class 'str'>
Reading Items
Indexing and slicing work the same way as with lists:
Example
colors = ("red", "green", "blue", "yellow")
print(colors[1])
print(colors[-1])
print(colors[1:3])
print("blue" in colors)green
yellow
('green', 'blue')
TrueTuples Cannot Change
Example
colors = ("red", "green", "blue")
colors[0] = "black"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
colors = ("red", "green", "blue")
temp = list(colors)
temp[0] = "black"
colors = tuple(temp)
print(colors)('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
student = ("Ayesha", 20, "BSCS")
name, age, program = student
print(name)
print(age)
print(program)Ayesha 20 BSCS
Use * to collect the remaining items into a list:
Example
scores = (95, 88, 76, 64, 50)
top, *others = scores
print(top)
print(others)95 [88, 76, 64, 50]
Tuple Methods
Tuples have only two methods:
| Method | What it does |
|---|---|
count(x) | How many times x appears |
index(x) | Position of the first x |
List or Tuple?
| Use a list when | Use a tuple when |
|---|---|
| Items will be added or removed | The data should stay fixed |
| Example: a shopping cart | Example: 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"?
