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:
alist = ['aa', ['b', 'c'], 'dd'] # Creating a nested listprint(alist)
The following illustration shows the structure of the list above:
Here’s another example of the structure of a nested list:
blist = ['0', '1', ['2.0', '2.1', ['2.2.0', '2.2.1']], '3', '4'] # creating a nested listprint(blist)
The following illustration shows the structure of the list above:
Here’s another example of a nested list:
clist = [[1,2,3],[4,5],[5],77,8.8,'ff'] # Creating a nested listprint(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.
alist = ['aa', ['b', 'c'], 'dd'] # Creating list 1blist = ['0', '1', ['2.0', '2.1', ['2.2.0', '2.2.1']], '3', '4'] # Creating list 2clist = [[1,2,3],[4,5],[5],77,8.8,'ff'] # Creating list 3dlist = [alist, blist, clist] # Creating list of listsprint(dlist)
In the code above:
- We create three lists:
alist
,blist
, andclist
. - We create a new list,
dlist
, with the help of the other lists using list initialization.