Python Tutorial Python Advanced Python References Python Libraries

Python - List of Lists



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

Create list of lists

Method 1: Using Lists as elements in final List

In the example below, lists p1, p2 and p3 are used as elements for final 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 Lists in final List

In the example below, lists p1, p2 and p3 are appended in the final 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 list using list comprehension.

def listoflists(lst):
  return [[item] for item in lst] 

person = ['John', 'Marry', 'Ramesh']
print(listoflists(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 list using python map() function.

def listoflists(lst):
  return list(map(lambda item:[item], lst))  

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

The code will give the following output:

[['John'], ['Marry'], ['Ramesh']]

❮ Python - Lists

5