How To Read A List Of Tuples In Python

In this tutorial, we will learn how to read a list of tuples in Python. Tuples are similar to lists, but they are immutable, which means they cannot be changed after they are created.

Reading a list of tuples is useful while working with structured data, be it from a file or an API where the data is organized in tuples. Let’s dive into the steps for reading and processing a list of tuples in Python.

Step 1: Define the list of tuples

First, we need to have our data organized in a list of tuples. In this example, let’s create a list of tuples, where each tuple contains a country’s name and its corresponding capital.

In this example, our data consists of 4 tuples, each with a country and its capital.

Step 2: Read the list of tuples

To read the list of tuples, you can use a simple for loop. The loop will iterate through the list of tuples, and you can extract individual elements of each tuple by using indexing.

This code will print each tuple in the list:

('USA', 'Washington, D.C.')
('France', 'Paris')
('Germany', 'Berlin')
('India', 'New Delhi')

Step 3: Access elements of the tuples

To access individual elements of each tuple (in this case, country and capital), you can use indexing inside the loop.

The output of this code will be:

Country: USA , Capital: Washington, D.C.
Country: France , Capital: Paris
Country: Germany , Capital: Berlin
Country: India , Capital: New Delhi

Another way to access elements of a tuple while iterating is using tuple unpacking. It allows you to assign variables directly to the individual tuple elements, thus making the code more readable.

This code produces the same output as the previous code block.

Full code:

Conclusion

In this tutorial, we learned how to read a list of tuples in Python using various methods. We first defined a list of tuples, iterated through the list, and accessed individual elements of the tuples using indexing and tuple unpacking.

Reading and processing lists of tuples is a common task in Python, especially when working with structured data. With this knowledge, you should now be better equipped to handle a list of tuples in your Python projects.