Python has several ways to group data items into structures. One of them is the tuple. In this tutorial, we will discuss what a python tuple is, and how to create and make use of tuples in our code.

What is a Tuple in Python?

A tuple is an ordered collection of values. With tuples, we can also store a collection of values in a single variable. However, lists also store multiple values in a single object. So how do tuples differ from lists?

Python Tuples vs Lists

There are some differences between tuples and lists. One difference is in syntax; A list is enclosed with square brackets, while a tuple is enclosed with parentheses. So, for instance (1, 3, 5) is a tuple, while [1, 3, 5] is a list.

Also, after a tuple has been created, it cannot be modified. That is why tuples are referred to as immutable data structures. Lists, on the other hand, are mutable; we can change an item in a list, add more items to a list, or even, remove items from a list.

Creating Python Tuples

A tuple can be created by enclosing items with parenthesis and separating each of them with commas. For example:


# defining a tuple
prime_tuple = (2, 3, 5, 7)

print(type(prime_tuple))

The following printout from the program confirms that the variable prime_tuple, is of type tuple.

Output:

<class 'tuple'>

To create an empty tuple, just write out a pair of parentheses with nothing in between.


# defining an empty tuple
empty_tuple = ()

print(type(prime_tuple))

Output:

<class 'tuple'>

In python, a pair of parentheses is also used to group expressions. What happens when we want to define a one-element tuple? We need a special syntax; place a comma after the element.


expr1 = ("Centauri")        # just a string expression
expr2 = ("Centauri", )      # a tuple with one element

print(type(expr1))
print(type(expr2))

Output:

<class 'str'>
<class 'tuple'>

expr1 contains a string, while expr2 contains a tuple, since we placed a comma after the item in parentheses. This syntactic difference allows python to differentiate between an expression in parentheses and a one-element tuple.

We can also create a tuple from a list by using the tuple() function.


# create a tuple from a list
num_list = [3, 7, 2, 4, 7]
print(f"Original list: {num_list}, type: {type(num_list)}")

num_tuple = tuple(num_list)
print(f"Converted list: {num_tuple}, type: {type(num_tuple)}")

The program converts a list object, num_list, into a tuple, num_tuple, by using tuple(). We can see this in the output.

Output:

Original list:  [3, 7, 2, 4, 7], type: <class 'list'> 
Converted list:  (3, 7, 2, 4, 7), type:  <class 'tuple'>

Number of Items in a Python Tuple

The len() function returns the number of elements in the tuple. If the tuple contains no elements, it returns 0.


# find out how many items in tuple
pythagorean_triple = (5, 12, 13)

print(f"{len(pythagorean_triple) = }")

Output:

len(pythagorean_triple) = 3

len() function returns 3 in the above example because the tuple only contains three items.

Tuple Assignment – Packing & Unpacking Python Tuples

Python provides two convenient ways to assign a tuple or its contents to variables. The concepts are Packing and Unpacking.

Packing Tuples in Python

When we assign multiple values, separated by commas, into a single variable, we are carrying out packing. We have already encountered packing when we were creating tuples. The next example will show another example of packing

# tuple packing assembles values into a tuple, and stores the tuple in a single variable
tuple_var1 = ('Akeem', 32, 'Prince' )

# the next line of code does exactly the same thing
tuple_var2 = 'Akeem', 32, 'Prince'

# both print statements will produce the same output
print(tuple_var1)
print(tuple_var1)

Output:

('Akeem', 32, 'Prince')
('Akeem', 32, 'Prince')

Unpacking Tuples in Python

Unpacking kind of does the opposite of packing; it stores each element of the tuple to a different variable in a single assignment statement.


# assign a tuple to a variable
vector_value = (2, 3, 6)

# unpacking a tuple extracts values from a tuple into variables
(x, y, z) = vector_value

# print out each component
print(f"{x}i + {y}j + {z}k")

Output:

2i + 3j + 6k

However, while unpacking a tuple, the number of variables to unpack into must be equal to the number of components, or elements, in the tuple. Otherwise, we will get a ValueError.

Accessing Elements in a Python Tuple

Every element in a tuple has a position or index, that be used to refer to it. The first element has an index of 0, while the last position has an index of (len(tuple) - 1). To access an element in a tuple, we need to specify the position/index using the index operator.


t = ("Harry", "Osborne", "Male", "New York", "Green Goblin")

# access via the index operator []
print(f"first item: {t[0]}")
print(f"last item: {t[len(t) - 1]}")

Output:

first item: Harry
last item: Green Goblin

While specifying index values, the indexes must lie between 0 and (len(tuple) - 1), otherwise, python will raise an IndexError exception.


# Index Error will occur if integer is out of range
print(t[9])

Output:

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in
1 # Index Error will occur if integer is out of range
----> 2 print(t[9])

IndexError: tuple index out of range

Accessing a Nested Python Tuple

Tuples can be nested. To access the elements of a nested tuple, we can either access the nested tuple first, then access its element, or use nested indexing.


student_offers_course = (("John", "Smith", 25, 2021), ("Introduction to Python", "CSC 211"))

# access in stages
course = student_offers_course[1] # store in variable first

print(f"course code = {course[1]}") # access with normal indexing

# access at once with nested indexing
print(f"course code = {student_offers_course[1][1]}")

Output:

course code = CSC 211
course code = CSC 211

From the output, we can see that the same element is accessed, whether we access in stages, or through nested indexing.

Negative indexing

Tuple positions are given from left to right, starting from 0, and increasing towards the last element. Tuples can also be accessed from right to left, where the last element has an index of -1, the second to the last an index of -2, and so on. With this Negative indexing, the first element will have an index of (- len(tuple)).


person = ("Jane", "Doe", "Female", 22, 5.5, "Houston", "Texas")

# get the last item
print(f"last item with normal indexing: {person[len(person) - 1]}")
print(f"last item with negative indexing: {person[-1]}")

print()

# get the first item
print(f"first item with normal indexing: {person[0]}")
print(f"first item with negative indexing: {person[-len(person)]}")

Output:

last item with normal indexing: Texas
last item with negative indexing: Texas

first item with normal indexing: Jane
first item with negative indexing: Jane

Slicing a Python Tuple

Python allows tuple slicing. When we slice a tuple, we are attempting to access a range of items in the tuple. The result returned is also a tuple containing the items in the selected range. To slice a tuple, we need to specify our start and end indexes, then python will return all items from positions start index of the range to (but excluding) the end index of the range.


# slicing, or accessing a range, using slice operator :
person = ("Jane", "Doe", "Female", 22, 5.5, "Houston", "Texas")

# get from third to last items
print(person[2:])

# get from third to fifth items
print(person[2:5])

# get from sixth to first
print(person[ :6])

Output:

('Female', 22, 5.5, 'Houston', 'Texas')
('Female', 22, 5.5)
('Jane', 'Doe', 'Female', 22, 5.5, 'Houston')

We can see from the example that when the end index of the range is not specified, slicing selects up to the last item in the tuple. Also, when we only specify the end index, slicing will select all elements from the first item in the tuple up to, but excluding, the end index.

Updating Tuple Elements

Tuples are immutable. This means that once created, we can either access them to get values, or delete them, but we cannot modify them. So the following attempt to update the tuple in the example will fail.


# updating tuples
student_offers_courses = ("Kumar", 23, ["Calculus", "Python", "Abstract Algebra"])

# tuples are immutable, so any attempt to update items directly fails
# try changing the course list (index = 2)
student_offers_courses[2] = ["Calculus", "Python", "C++"]

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
4 # tuples are immutable, so any attempt to update items directly fails
5 # try changing the course list (index = 2)
----> 6 student_offers_courses[2] = ["Calculus", "Python", "C++"]

TypeError: 'tuple' object does not support item assignment

However, we can modify a tuple element that is a mutable data structure (like lists).The next example shows how to do this.


student_offers_courses = ("Kumar", 23, ["Calculus", "Python", "Abstract Algebra"])

# even though tuples are immutable, it is possible to modify its mutable element; the list
# try changing the course "Abstract Algebra" to "C++" by nested indexing
student_offers_courses[2][2] = "C++"

print(student_offers_courses)

Output:

('Kumar', 23, ['Calculus', 'Python', 'C++'])

Deleting a Python Tuple

Since tuples are immutable, we can only delete the whole tuple, not individual items. The following code will fail since it attempts to delete an item from the tuple.


student_offers_courses = ("Kumar", 23, ["Calculus", "Python", "Abstract Algebra"])

# tuples are immutable, so items cannot be added or removed
# try to delete the age
del student_offers_courses[1]

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
3 # tuples are immutable, so items cannot be added or removed
4 # try to delete the age
----> 5 del student_offers_courses[1]

TypeError: 'tuple' object doesn't support item deletion

The next code successfully deletes the whole tuple. The error message is just trying to tell us that we succeeded in deleting the tuple.


student_offers_courses = ("Kumar", 23, ["Calculus", "Python", "Abstract Algebra"])

# try to delete the whole tuple
del student_offers_courses

print(student_offers_courses) # will throw an exception because del was successful

Output:

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
2 del student_offers_courses
3
----> 4 print(student_offers_courses)

NameError: name 'student_offers_courses' is not defined

Python | Sort Tuple

If we need the values in a tuple to be sorted, we could make use of the sorted() function.


# sort a tuple
num_tuple = (8, 3, 4, 9, 1, 3, 2, 4)
sorted_result = sorted(num_tuple)
sorted_tuple = tuple(sorted_result)

print(f"Unsorted tuple: {num_tuple}")
print(f"Sorted tuple: {sorted_tuple}")

sorted() actually returns a list containing sorted elements from the list. If we need the final result to be a tuple, we need to convert the list back to a tuple by using the tuple() built-in function. The code produces the following output:

Output:

Unsorted tuple: (8, 3, 4, 9, 1, 3, 2, 4)
Sorted tuple: (1, 2, 3, 3, 4, 4, 8, 9)

We can also call sorted() with an extra parameter, reverse. Setting reverse to True causes the tuple to be sorted in descending order.


# sort a tuple
num_tuple = (8, 3, 4, 9, 1, 3, 2, 4)
sorted_result = sorted(num_tuple, reverse=True)
sorted_tuple = tuple(sorted_result)

print(f"Unsorted tuple: {num_tuple}")
print(f"Sorted tuple: {sorted_tuple}")

Output:

Unsorted tuple: (8, 3, 4, 9, 1, 3, 2, 4)
Sorted tuple: (9, 8, 4, 4, 3, 3, 2, 1)

Conclusion

This tutorial discussed python tuples and how to make them in code. Thanks for reading!

If you need homework help python or looking for someone who can python help then feel free to drop us a message.

Like this article? Follow us on Facebook and LinkedIn.