Search⌘ K
AI Features

Nested Lists

Explore the concept of nested lists in Python, including how to create and access lists within lists. Understand their use for representing matrices and practice writing programs to calculate sums of rows and columns, enhancing your Python list manipulation skills.

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:

Python 3.10.4
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:

Python 3.10.4
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:

Python 3.10.4
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.

Python 3.10.4
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.

A mathematical matrix is implemented as a nested list in Python, as shown in the following example:

matrixA=[123456789101112] matrixA = \begin{bmatrix} 1&2&3&4 \\ 5&6&7&8 \\ 9&10&11&12 \end{bmatrix}

Python 3.10.4
matrixA = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # Creating a matrix
print("Matrix:",matrixA)

The variable, matrixA, is a list of three elements, and each element is itself a list of four elements.

The following code demonstrates a way to write values in the forms of rows and columns. It only adds convenience for the reader of the program. The output will remain the same.

Python 3.10.4
matrixB = [ [10,12,13,14],
[15,16,17,18],
[19,20,21,22] ]
print("Matrix:",matrixB)

The result of the second program is exactly the same as the result of the first program. Inside the computer’s memory, both variables (matrixA and matrixB) are stored in the same way, as linear sequences. Now, let’s say we want to concatenate these two matrixes into another matrix (matrixC).

Python 3.10.4
matrixA = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
matrixB = [ [10,12,13,14],
[15,16,17,18],
[19,20,21,22] ]
matrixC = matrixA + matrixB # Adding matrix A and matrix B
print("Matrix:",matrixA)
print("Matrix:",matrixB)
print("Matrix:",matrixC)

The resulting matrix isn’t a sum of the values of operands. We need to access the individual integer values in each matrix to produce their sum.

Individual values in nested lists

The individual values in a nested list are accessed through multiple index numbers used in a row. Let’s take the example of the following list:

list1 = [0, 1, [20, 21, [220, 221]], 3, 4]
  • list1 is a nested list.
  • The value 20 can be accessed as list1 [ 2 ] [ 0 ], and the value 221 can be accessed as list1 [2] [2] [1].
  • The values that are not nested in list1 can be accessed with a single index number. For example, list1[4] is 4.
  • The number of indices depends on the level of nesting.

The following illustration shows the structure of the list above. The main level elements are list1[0] , list1[1], list1[3], and list1[4]. The element list1[2] has another sublist, and the elements of the sublist can be accessed as list1[2][0] and list1[2][1]. The last element list1[2][2] has another sublist, and the elements can be accessed as list1[2][2][0] and list1[2][2][1].

The following program calculates the sum of two matrix variables:

Python 3.10.4
a = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
b = [ [1,2,3,4],
[5,6,7,8],
[9,10,11,12] ]
c = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] #Creating a matrix c of zeros
print("Matrix:",a)
print("Matrix:",b)
rows,cols = 3,4
for i in range(rows): # Outer loop for rows
for j in range(cols): # Inner loop for columns
c[i][j] = a[i][j] + b[i][j] # Adding values of matrix a and b and assigning the result in matrix c
print("Matrix Sum:",c)

In the program above:

  • We declare and initialize two matrixes, a and b.
  • We define another matrix, c, initialized with zeros.
  • We traverse the individual values of b to add the corresponding values of c.
  • The variable rows is 3, which represents the number of rows of the matrix.
  • The variable cols is 4, which represents the number of columns of the matrix.

Practice nested lists

Here are a few example programs to practice using nested lists in Python. By clicking the “Show Solution” button, you can find a program that solves the respective problem. You can copy and paste the given solution into the code widget to make sure the output of your solution matches the given solution. There can be several ways of writing correct solutions in programming.

Calculate the sum of each row in a matrix

Write a program to show the sum of each row of the matrix. The matrix must have two rows and three columns.

Sample input 1

[[10,20,30],
 [40,50,60]]

Sample output 1

Matrix: [[10, 20, 30], [40, 50, 60]]
Sum of Row1: 60
Sum of Row2: 150

Sample input 2

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

Sample output 2

Matrix: [[1, 2, 3], [4, 5, 6]]
Sum of Row1: 6
Sum of Row2: 15
Python 3.10.4
# Write your code here

Calculate the sum of each column in a matrix

Write a program to show a matrix in the form of rows and columns, then show the sum of each column. The matrix must have five rows and ten columns.

Sample input

[[0,1,2,3,4,5,6,7,8,9],
[10,11,12,13,14,15,16,17,18,19],
[20,21,22,23,24,25,26,27,28,29],
[30,31,32,33,34,35,36,37,38,39],
[40,41,42,43,44,45,46,47,48,49]]

Sample output

Displaying in the matrix form:

row# 0    ==>    0	1	2	3	4	5	6	7	8	9	
row# 1    ==>    10	11	12	13	14	15	16	17	18	19	
row# 2    ==>    20	21	22	23	24	25	26	27	28	29	
row# 3    ==>    30	31	32	33	34	35	36	37	38	39	
row# 4    ==>    40	41	42	43	44	45	46	47	48	49	

Column Sums are: [100, 105, 110, 115, 120, 125, 130, 135, 140, 145]
Python 3.10.4
# Write your code here