Python - List List Nesting

Introduction

We can have a list that contains a dictionary, which contains another list, and so on.

To represent matrix, or "multidimensional arrays" in Python, we can nest lists:

Demo

M = [[1, 2, 3],               # A 3 ? 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] # w w w .  ja  v  a2 s .  co  m
print( M )

Result

Here, we've coded a list that contains three other lists.

The effect is to represent a 3 by 3 matrix of numbers.

Such a structure can be accessed in a variety of ways:

Demo

M = [[1, 2, 3],               # A 3 by 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] #  w  ww.  j  a v  a 2  s. c o  m

print( M[1] )                          # Get row 2 
print( M[1][2] )                       # Get row 2, then get item 3 within the row

Result

The first operation fetches the entire second row, and the second grabs the third item within that row.

The following code represents matrixes, multidimensional arrays, in Python is as lists with nested sublists.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

With one index, you get an entire row, the nested sublist, and with two, you get an item within the row:

Demo

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
print( matrix[1] )
print( matrix[1][1] )
print( matrix[2][0] )

matrix = [[1, 2, 3], # from w w w  . j  av a 2  s  .  c  o  m
          [4, 5, 6], 
          [7, 8, 9]] 
print( matrix[1][1] )

Result