Two Dimensional Lists Introduction

Download Report

Transcript Two Dimensional Lists Introduction

Lists in Python
Two-dimensional arrays
Two dimensions
• You will sometimes have data which has a
two-dimensional structure (days and hours for
example, or rows and columns)
• You could store the data in one big list and
keep track of the structure some other way
but most modern languages provide a way to
express the two dimensions directly
List of lists
• In Python you can think of this structure as a
list of lists
• mat = [[1,2,3], [5, 9, 2], [7, 8, 3], [6, 7, 0]]
• Of course in Python any of these lists can be
any size (they don’t all have to be 3 elements
long!)
• Typically a 2-d array is thought of as having so
many rows and so many columns (a grid like
Excel)
Syntax of 2-d arrays
• One way to create a 2-d array is as given on
the last slide, just write it out
• Another that is quicker if you want to initialize
all elements to one value:
– mat2 = [[0] * 3 for i in range(4)]
creates a 2-d array with 4 rows, 3 columns full of zeros
0
0
0
0
0
0
0
0
0
0
0
O
Accessing elements of a 2-d array
• You use two subscripts, each in a pair of []
• mat [2][1] is the element in the third row and
second column – just like 1-d arrays, they start
numbering at [0][0]