Create a Nested List in Python

A list is a collection of multiple distinct elements while a nested list is a list in python which contains another list within itself. We have many ways to create a nested list in Python, few of them are explained below.

How to Create a Nested List in Python

List Initializer

Example

lst1 = [1,2,3,4]
lst2 = [5,6,7,8]
# will create list of lists
lst3 = [lst1, lst2]
# Display result
print(lst3)

Code Explanation

We created 2 lists and stored both lists in another list so it will become a nested list. Check out the output below.

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

Nested List by Append Method

Example

lst1 = [11,12,13,14]
lst2 = [15,16,17,18]
lst3 = [] # empty list
# will create list of lists
lst3.append(lst1)
lst3.append(lst2)
print(lst3)

Code Explanation

In the above example, we created 2 lists, then we declared an empty list, and then we used the append method of python which will return a nested list as a result, check out the output below.

Output

[[11, 12, 13, 14], [15, 16, 17, 18]]

Nested List By Index Method

Example

# creating list
nestList = [11, 12, ['b', 11], 13]

# indexing inner list: 
subL = nestList[3]

# accessing 1st element of list:
listelem = nestList[2][0] 

print("List inside the inner list: ", subL)
print("1st element of  inner list: ", listelem)

Code Explanation

In the above code, we declared a nested list then we declared the index number of the element from the inner list, after that, we declared an index number from the outer list, by following this indexing method we can check the nested elements. Check out the result below.

Output

List inside the inner list:  13
1st element of  inner list:  b

Conclusion

In this tutorial, we discussed How to Create a Nested List in Python.

We talked about the difference between an ordinary list and a nested list in python, then we discussed the initialize method for creating a nested list with an example after that we used the append method and practice its example, we also see the usage of the index method.

Hope you like the tutorial if you have any queries regarding this article so feel free to contact us below. Thanks for reading.

Leave a Comment