Python List of Tuples

List of Tuples in Python

List is a collection of items. And tuple can be considered as an item. So, you can have a List of Tuples in Python.

In this tutorial, we will learn how to initialize a list of tuples and some of the operations on this list of tuples.

Initialize a list of tuples

Following is an example to initialize a list of tuples. We have a list enclosed in square brackets, where each element is a tuple.

list_of_tuples = [(1,'apple',92), (2,'banana',95), (3,'cherry',93)]

In the above list, we have three tuples in the list.

Append a tuple to list of tuples

Use append() method to append an item to the list, in this case the item is a tuple.

Python Program

list_of_tuples = [(1,'apple',92), (2,'banana',95), (3,'cherry',93)]
list_of_tuples.append((4, 'mango', 94))
print(list_of_tuples)
Run Code Copy

Output

[(1, 'apple', 92), (2, 'banana', 95), (3, 'cherry', 93), (4, 'mango', 94)]

Update a tuple in the list of tuples

You can replace a tuple with other tuple, but not modify a tuple in-place in the list, because tuples are immutable.

Python Program

list_of_tuples = [(1,'apple',92), (2,'banana',95), (3,'cherry',93)]
list_of_tuples[1] = (4, 'mango', 94)
print(list_of_tuples)
Run Code Copy

Output

[(1, 'apple', 92), (4, 'mango', 94), (3, 'cherry', 93)]

Remove a Tuple from List of Tuples

You can use del keyword to remove any tuple, using index, from a list of tuples, as shown in this example program.

Python Program

list_of_tuples = [(1,'apple',92), (2,'banana',95), (3,'cherry',93)]

# Delete second item from list
del list_of_tuples[1]
print(list_of_tuples)
Run Code Copy

Output

[(1, 'apple', 92), (3, 'cherry', 93)]

Summary

In this tutorial of Python Examples, we learned how to initialize, access and modify a list of tuples, with the help of well detailed Python example programs.

Related Tutorials

Code copied to clipboard successfully 👍