Nested Lists

Learn to use lists of lists in Python.

What is a nested list?

In Python, a nested list is a list that contains other lists as its values or members. The container list is termed an outer list, and the member list is termed an inner list. A list is said to be a nested list if it has another list as one or more of its members, even if all other members of the outer list are not lists.

The general concepts of two-dimensional arrays, n-dimensional arrays, or jagged arrays are implemented as nested lists in Python. The following program illustrates the structure of a nested list:

Press + to interact
alist = ['aa', ['b', 'c'], 'dd'] # Creating a nested list
print(alist)

The following illustration shows the structure of the list above:

Here’s another example of the structure of a nested list:

Press + to interact
blist = ['0', '1', ['2.0', '2.1', ['2.2.0', '2.2.1']], '3', '4'] # creating a nested list
print(blist)

The following illustration shows the structure of the list above:

Here’s another example of a nested list:

Press + to interact
clist = [[1,2,3],[4,5],[5],77,8.8,'ff'] # Creating a nested list
print(clist)

The following illustration shows the structure of the above list.

We can also create a new list, dlist, with the help of all the lists above (alist, blist, and clist), using list initialization.

Press + to interact
alist = ['aa', ['b', 'c'], 'dd'] # Creating list 1
blist = ['0', '1', ['2.0', '2.1', ['2.2.0', '2.2.1']], '3', '4'] # Creating list 2
clist = [[1,2,3],[4,5],[5],77,8.8,'ff'] # Creating list 3
dlist = [alist, blist, clist] # Creating list of lists
print(dlist)

In the code above:

  • We create three lists: alist, blist, and clist.
  • We create a new list, dlist, with the help of the other lists using list initialization.
...