C++ - Q&A

Python - List of Tuples



A list of tuples is a list which contains tuple as elements. There are many ways through which a list of tuples can be created in Python. Few ways are mentioned below:

Create list of tuples

Method 1: Using Tuples as elements in the List

In the example below, tuples p1, p2 and p3 are used as elements for list person.

p1 = ('John', 25, 'London')
p2 = ('Marry', 27, 'Paris')
p3 = ('Ramesh', 26, 'Delhi')

person = [p1, p2, p3]
print(person)

The above code will give the following output:

[('John', 25, 'London'), ('Marry', 27, 'Paris'), ('Ramesh', 26, 'Delhi')]

Method 2: Appending Tuples in the List

In the example below, tuples p1, p2 and p3 are appended in the list person one by one.

p1 = ('John', 25, 'London')
p2 = ('Marry', 27, 'Paris')
p3 = ('Ramesh', 26, 'Delhi')

person = []
person.append(p1)
person.append(p2)
person.append(p3)

print(person)

The output of above code will be:

[('John', 25, 'London'), ('Marry', 27, 'Paris'), ('Ramesh', 26, 'Delhi')]

Method 3: Using List comprehension

In this example, all element of list person is converted into a tuple using list comprehension.

def listoftuples(lst):
  return [(item,) for item in lst] 

person = ['John', 'Marry', 'Ramesh']
print(listoftuples(person))

The code will give the following output:

[('John',), ('Marry',), ('Ramesh',)]

Method 4: Using map() function

In this example, all element of list person is converted into a tuple using python map() function.

def listoftuples(lst):
  return list(map(lambda item:(item,), lst))  

person = ['John', 'Marry', 'Ramesh']
print(listoftuples(person))

The code will give the following output:

[('John',), ('Marry',), ('Ramesh',)]