5.16 Two-Dimensional Lists

  • Lists can contain other lists as elements.
  • Typical use is to represent tables of values consisting of information arranged in rows and columns.
  • To identify a particular table element, we specify two indices—the first identifies the element’s row, the second the element’s column.

Creating a Two-Dimensional List

In [1]:
a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]]

Writing the list as follows makes its row and column tabular structure clearer:

a = [[77, 68, 86, 73],  # first student's grades
     [96, 87, 89, 81],  # second student's grades 
     [70, 90, 86, 81]]  # third student's grades

Illustrating a Two-Dimensional List

The two-dimensional list 'a' with its rows and columns of exam grade values

Identifying the Elements in a Two-Dimensional List

The two-dimensional list 'a' labeled with the names of its elements

  • Output the rows of the preceding two-dimensional list.
In [2]:
for row in a:
    for item in row:
        print(item, end=' ')
    print()
        
77 68 86 73 
96 87 89 81 
70 90 86 81 

How the Nested Loops Execute

In [3]:
for i, row in enumerate(a):
    for j, item in enumerate(row):
        print(f'a[{i}][{j}]={item} ', end=' ')
    print()
a[0][0]=77  a[0][1]=68  a[0][2]=86  a[0][3]=73  
a[1][0]=96  a[1][1]=87  a[1][2]=89  a[1][3]=81  
a[2][0]=70  a[2][1]=90  a[2][2]=86  a[2][3]=81  
  • Outer for statement iterates over the list’s ows one row at a time.
  • During each iteration of the outer for statement, the inner for statement iterates over each column in the current row.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.