1 of 43

CSc 110

2D Lists

Benjamin Dicken

2 of 43

2D Lists!

  • We’ve used lists (1 dimensional lists) in this class so far
  • Today:Use two-dimensional lists!
  • The concepts discussed here can actually extend to N-dimensional lists, but I’ll mostly stick to 2D
  • 2D lists useful for reading in CSV files manually

3 of 43

Review

Should be familiar with this kind of list usage:

items = [5, 10, 20, 6, 7, 8]

items[0] = 10

items[1] = 3

items[4] = 99

print(str(items))

index

0

1

2

3

4

5

value

10

3

20

6

99

8

4 of 43

2D list

  • To create a 2D list, we are, create a list-of-lists
  • For example, this list

items = [[9, 8, 7, 8], [10, 20, 30, 4], [5, 50, 55, 4]]

  • Can be represented by this diagram

idxs

0

1

2

3

0

9

8

7

8

1

10

20

30

4

2

5

50

55

4

5 of 43

2D list

items = [[9, 8, 7, 8],

[10, 20, 30, 4],

[5, 50, 55, 4]]

  • The “first dimension” is the outer list
  • The “second dimension” are each of the inner lists
  • When we draw pictures of 2D lists, the first dimension is the vertical axis, the second is the horizontal
  • Notice how the list can be formatted to reflect the 2D diagram

idxs

0

1

2

3

0

9

8

7

8

1

10

20

30

4

2

5

50

55

4

6 of 43

2D list

What will each of the below list accesses evaluate to?

val_a = items[0][0]

val_b = items[2][3]

val_c = items[1][2]

print(val_a, val_b, val_c)

items = [[9, 8, 7, 8],

[10, 20, 30, 4],

[5, 50, 55, 4]]

idxs

0

1

2

3

0

9

8

7

8

1

10

20

30

4

2

5

50

55

4

Activity

7 of 43

Which lookups are valid?

val_a = items[1][5] # ?

val_b = items[2][5] # ?

val_c = items[3][2] # ?

items = [[9, 7, 8],

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

[5],

[10, 20, 30]]

idxs

0

1

2

3

4

5

0

9

7

8

1

1

2

3

4

5

6

2

5

3

10

20

30

Activity

8 of 43

Which lookups are valid?

val_a = items[1][5] # OK

val_b = items[2][5] # NOT OK

val_c = items[3][2] # OK

items = [[9, 7, 8],

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

[5],

[10, 20, 30]]

idxs

0

1

2

3

4

5

0

9

7

8

1

1

2

3

4

5

6

2

5

3

10

20

30

9 of 43

What will it print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

l1 = names[1][0][2]

l2 = names[2][1][2]

l3 = names[0][1][4]

print(l1 + l2 + l3)

Activity

10 of 43

2D list

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

names ==

names[2] ==

names[2][1] ==

names[2][1][0] ==

[["Ric", "Janet", "Joe"], ["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

["Cam", "Jan", "Jane"]

"Jan"

"J"

  • 2D lists of strings are kind-of like a 3D list
  • The first 2 dimensions are the lists, the last is the characters of the string

11 of 43

Traversing a 2d List

  • As with regular lists, it is often useful to iterate (loop) through all of the elements in a 2D list
  • This can be achieved in a few ways
    • Using the indexes
    • Using the actual values
  • There are advantages to each one

12 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

print(i)

Activity

13 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

print(i)

['Ric', 'Janet', 'Joe']

['Ike', 'Alan', 'Ko']

['Cam', 'Jan', 'Jane']

14 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in names:

print(i)

Activity

15 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in names:

print(i)

['Ric', 'Janet', 'Joe']

['Ric', 'Janet', 'Joe']

['Ric', 'Janet', 'Joe']

['Ike', 'Alan', 'Ko']

['Ike', 'Alan', 'Ko']

['Ike', 'Alan', 'Ko']

['Cam', 'Jan', 'Jane']

['Cam', 'Jan', 'Jane']

['Cam', 'Jan', 'Jane']

16 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in names:

print(j)

Activity

17 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in names:

print(j)

['Ric', 'Janet', 'Joe']

['Ike', 'Alan', 'Ko']

['Cam', 'Jan', 'Jane']

['Ric', 'Janet', 'Joe']

['Ike', 'Alan', 'Ko']

['Cam', 'Jan', 'Jane']

['Ric', 'Janet', 'Joe']

['Ike', 'Alan', 'Ko']

['Cam', 'Jan', 'Jane']

18 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in i:

print(j)

Activity

19 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in i:

print(j)

Ric

Janet

Joe

Ike

Alan

Ko

Cam

Jan

Jane

20 of 43

What would you change?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in i:

print(j)

Ric Janet Joe

Ike Alan Ko

Cam Jan Jane

Ric

Janet

Joe

Ike

Alan

Ko

Cam

Jan

Jane

Activity

21 of 43

What would you change?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in names:

for j in i:

print(j + '\t', end='')

print()

Ric Janet Joe

Ike Alan Ko

Cam Jan Jane

Ric

Janet

Joe

Ike

Alan

Ko

Cam

Jan

Jane

22 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in range(0, len(names)):

for j in range(0, len(names[i])):

print(names[i][j], end="\t")

print()

Activity

23 of 43

What will this print?

names = [["Ric", "Janet", "Joe"],

["Ike", "Alan", "Ko"],

["Cam", "Jan", "Jane"]]

for i in range(0, len(names)):

for j in range(0, len(names[i])):

print(names[-j-1][i], end="\t")

print()

Activity

24 of 43

CSV

  • The CSV file format is a common way to represent tabular data
    • Comma-Separated Values
    • Regular text files, with particular rules about how the data within it is formatted
      • Useful analogy: text representation of a excel spreadsheet

25 of 43

CSV Formatting

  • Each line of the file representa a “row”
  • Each line has value(s) separated by commas
  • Each line should have the same number of columns
  • The first line can (optionally) be a titles for each column

26 of 43

CSV Grades example

Name,SID,exam1,exam2,final

Steve,1429,67,84,91

Annie,3211,81,85,85

James,3171,90,75,80

Carlita,7877,85,87,89

27 of 43

CSV Grades example (students.csv)

Name,SID,exam1,exam2,final

Steve,1429,67,84,91

Annie,3211,81,85,85

James,3171,90,75,80

Carlita,7877,85,87,89

Optional row of column titles

Each row represents a row of data (an entry in the student table

Each row has the same number of columns - to match the titles

28 of 43

CSV Grades example (students.csv)

Steve,1429,67,84,91

Annie,3211,81,85,85

James,3171,90,75,80

Carlita,7877,85,87,89

Title row is optional

Each row represents a row of data (an entry in the student table

Each row has the same number of columns - to match the titles

29 of 43

Load the contents of csv file into list

csv_data = []

# What should go here?

1,4,7,2

3,10,20,30

3,4,7,1

1,1,1,2

1,5,5,1

0,1,0,1

numbers.csv

Activity

30 of 43

Load the contents of csv file into list

csv_data = []

csv_file = open('numbers.csv', 'r')

# What should go here?

1,4,7,2

3,10,20,30

3,4,7,1

1,1,1,2

1,5,5,1

0,1,0,1

numbers.csv

31 of 43

Load the contents of csv file into list

csv_data = []

csv_file = open('numbers.csv', 'r')

for line in csv_file:

line = line.strip('\n')

values = line.split(',')

# What should go here?

1,4,7,2

3,10,20,30

3,4,7,1

1,1,1,2

1,5,5,1

0,1,0,1

numbers.csv

32 of 43

Load the contents of csv file into list

csv_data = []

csv_file = open('numbers.csv', 'r')

for line in csv_file:

line = line.strip('\n')

values = line.split(',')

csv_data.append(values)

1,4,7,2

3,10,20,30

3,4,7,1

1,1,1,2

1,5,5,1

0,1,0,1

numbers.csv

33 of 43

Load the contents of csv file into list

csv_data = []

csv_file = open('numbers.csv', 'r')

for line in csv_file:

line = line.strip('\n')

values = line.split(',')

csv_data.append(values)

1,4,7,2

3,10,20,30

3,4,7,1

1,1,1,2

1,5,5,1

0,1,0,1

numbers.csv

What type are the values in the 2D list?

Activity

34 of 43

Load the contents of csv file into list

csv_data = []

csv_file = open('numbers.csv', 'r')

for line in csv_file:

line = line.strip('\n')

values = line.split(',')

num_vals = []

for i in values:

num_vals.append( int(i) )

csv_data.append(num_vals)

1,4,7,2

3,10,20,30

3,4,7,1

1,1,1,2

1,5,5,1

0,1,0,1

numbers.csv

35 of 43

Flip the order U/D

csv_data = []

## Assume that the data has

## already been read in to

## csv_data

# (1) First, flip the rows

# (2) Then, print them out

1,4,7,2

1,5,5,1

0,1,0,1

numbers.csv

0 1 0 1

1 5 5 1

1 4 7 2

output

Activity

36 of 43

Flip the order U/D

csv_data = []

flipped = []

for i in range(0, len(csv_data)):

ni = -1 - i

flipped.append( csv_data[ni] )

# (2) Then, print them out

1,4,7,2

1,5,5,1

0,1,0,1

numbers.csv

0 1 0 1

1 5 5 1

1 4 7 2

output

37 of 43

Flip the order U/D

csv_data = []

flipped = []

for i in csv_data:

flipped.insert(0, i)

# (2) Then, print them out

1,4,7,2

1,5,5,1

0,1,0,1

numbers.csv

0 1 0 1

1 5 5 1

1 4 7 2

output

38 of 43

Flip the order U/D

csv_data = []

flipped = []

for i in csv_data:

flipped.insert(0, i)

for i in flipped:

for j in i:

print(str(j) + ' ', end='')

print()

1,4,7,2

1,5,5,1

0,1,0,1

numbers.csv

0 1 0 1

1 5 5 1

1 4 7 2

output

39 of 43

Graphical Stock Plotter

40 of 43

Graphical Stock Plotter

red,apple,100,125,120,95,130,145,170,130,150,177,230,260

blue,exxon,60,67,72,81,80,72,68,64,64,70,72,68

green,toyota,20,27,17,32,50,58,67,82,85,90,99,105

stocks.csv

41 of 43

Graphical Stock Plotter

red,apple,100,125,120,95,130,145,170,130,150,177,230,260

blue,exxon,60,67,72,81,80,72,68,64,64,70,72,68

green,toyota,20,27,17,32,50,58,67,82,85,90,99,105

stocks.csv

* Download plot.py

* Implement main

Activity

42 of 43

from graphics import graphics

def get_stock_data():

f = open('stocks.csv', 'r')

data = []

for line in f:

row = []

sp = line.split(',')

row.append(sp[0])

row.append(sp[1])

for element in sp[2:]:

row.append(int(element))

data.append(row)

return data

def main():

stock_data = get_stock_data()

gui = graphics(600, 300, 'stocks')

i = 0

while i < len(stock_data):

print(stock_data[i])

color = stock_data[i][0]

# TODO: Draw the label

j= 0

while j < len(stock_data[i])-2:

x = 10 + (j*50)

y = -(stock_data[i][j+2]-300)

# TODO: Draw the line

# TODO: Draw the dot

j += 1

i += 1

main()

43 of 43

from graphics import graphics

def get_stock_data():

f = open('stocks.csv', 'r')

data = []

for line in f:

row = []

sp = line.split(',')

row.append(sp[0])

row.append(sp[1])

for element in sp[2:]:

row.append(int(element))

data.append(row)

return data

def main():

stock_data = get_stock_data()

gui = graphics(600, 300, 'stocks')

i = 0

while i < len(stock_data):

print(stock_data[i])

color = stock_data[i][0]

gui.text(5, 5+30*i, stock_data[i][1], color, 25)

j= 0

prev_x = -1

prev_y = -1

while j < len(stock_data[i])-2:

x = 10 + (j*50)

y = -(stock_data[i][j+2]-300)

if prev_x >= 0:

gui.line(prev_x, prev_y, x, y, color, 2)

gui.ellipse(x, y, 10, 10, color)

prev_x = x

prev_y = y

j += 1

i += 1

main()