Print a List of Tuples in Python
The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ].
Using print()
print() function is the most efficient way to print the entire list of tuples as it is. This method displays the list in its default string representation.
# list of tuples
a = [(1, 'DSA'), (2, 'Java'), (3, 'Python')]
print(a)
Output
[(1, 'DSA'), (2, 'Java'), (3, 'Python')]
Using for Loop
This method involves iterating over each tuple in the list and printing it individually. It provides a more readable output, especially when each tuple holds distinct pieces of information.
# list of tuples
a = [(1, 'DSA'), (2, 'Java'), (3, 'Python')]
for item in a :
print(item)
Output
(1, 'DSA') (2, 'Java') (3, 'Python')
Using pprint module
pprint module stands for “pretty-print”. It provides a more structured and readable output for complex or nested data structures like lists of tuples. It is especially useful when the data structure is large or contains deeply nested elements.
# importing pprint module
import pprint
# list of tuples
a = [(1, 'DSA'), (2, 'Java'), (3, 'Python')]
pprint.pprint(a)
Output
[(1, 'DSA'), (2, 'Java'), (3, 'Python')]
Using List Comprehension
List comprehension is usually used to create lists, but it can also be misused to print elements. This approach prints each tuple while creating an unnecessary list of None values as a side effect.
# list of tuples
a = [(1, 'DSA'), (2, 'Java'), (3, 'Python')]
[print(item) for item in a ]
Output
(1, 'DSA') (2, 'Java') (3, 'Python')