Print a list of tuples in Python

In this article, we will discuss how to print a list of tuples in Python.

Table Of Contents

Method 1: Print list of tuples using for-loop

Iterate over all tuples in list using a for-loop, and print each tuple in a separate line. To print the contents of each tuple, apply astrik operator on tuple to decouple all elements in it, and pass them to print() function. Let’s see some examples,

Example 1

students = [(11, 'Ritika', 'Delhi'),
            (12, 'Smriti', 'New York'),
            (13, 'Shaun',  'London'),
            (14, 'MARK',   'Tokyo')]

for tupleObj in students:
    print(*tupleObj)

Output:

11 Ritika Delhi
12 Smriti New York
13 Shaun London
14 MARK Tokyo

Example 2

students = [(11, 'Ritika', 'Delhi'),
            (12, 'Smriti', 'New York'),
            (13, 'Shaun',  'London'),
            (14, 'MARK',   'Tokyo')]

for tupleObj in students:
    print(tupleObj[0], tupleObj[1], tupleObj[2])

Output:

11 Ritika Delhi
12 Smriti New York
13 Shaun London
14 MARK Tokyo

Method 2: Print list of tuples with header row

Suppose we have a list of tuples, and a list of strings. Elements in the second list should be printed as header, and tuples in first list should be printed as rows. For this, first we will print the list of header items ina tabular format. Then we will iterate over all tuples in list, and print the content of each tuple i tabular format. Let’s see an example,

students = [(11, 'Ritika', 'Delhi'),
            (12, 'Smriti', 'New York'),
            (13, 'Shaun',  'London'),
            (14, 'MARK',   'Tokyo')]

heading = ['ID', 'Name', 'City']

print(f'{heading[0]: <10}{heading[1]: <10}{heading[2]: <10}')

for student in students:
    print(f'{student[0]: <10}{student[1]: <10}{student[2]: <10}')

Output:

ID        Name      City      
11        Ritika    Delhi     
12        Smriti    New York  
13        Shaun     London    
14        MARK      Tokyo    

Method 3: Print list of tuples using join() function

We can join all the tuples in list into a single string. While joining, we will use the newline character as separator, therefore all the tuples will be in separate lines. Let’s see an example,

students = [(11, 'Ritika', 'Delhi'),
            (12, 'Smriti', 'New York'),
            (13, 'Shaun',  'London'),
            (14, 'MARK',   'Tokyo')]

strValue = '\n'.join(str(tupleObj) for tupleObj in students)

print(strValue)

Output:

(11, 'Ritika', 'Delhi')
(12, 'Smriti', 'New York')
(13, 'Shaun', 'London')
(14, 'MARK', 'Tokyo')

Summary

We learned about different ways to print a list of tuples in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top