Presentation is loading. Please wait.

Presentation is loading. Please wait.

2-Dimensional Lists (Matrices) in Python

Similar presentations


Presentation on theme: "2-Dimensional Lists (Matrices) in Python"— Presentation transcript:

1 2-Dimensional Lists (Matrices) in Python

2 List Review emptyList = [] print(len(emptyList)) #displays 0, the size of emptyList myList = [8, 6, 7, 5, 3, 0, 9] print(myList[0]) #displays 8 by accessing the 0th-element print(myList[3]) #displays 5 by accessing the 3th-element print(len(myList)) #displays 7, the size of myList myList[5] = 4 #changes the 0 in the list to 4 #[8, 6, 7, 5, 3, 4, 9]

3 What if elements in a list are lists?
matrix = [ [1, 3, 5], [2, 4, 6] ] print(matrix[0]) #gives you the entire 0th-element, which is [1, 3, 5] # How do we access an element inside of the inner list? # Use a second set of brackets to access an inner list’s elements print(matrix[0][1]) #gives you 3

4 Another way to show a 2-D list
matrix = [ [1, 5, 9], [2, 4, 6], [8, 5, 3] ] # This looks a little more aesthetic and easier to read # Each inner list is a row # Within each row are column elements # Access individual elements by using matrix[ROW][COL]

5 Changing elements matrix = [ [1, 5, 9], [2, 4, 6], [8, 5, 3] ] matrix[2][1] = 0 #changes the row-2, col-1 to 0 #[ [1, 5, 9], # [2, 4, 6], # [8, 0, 3] ]

6 len() and matrices matrix = [ [1, 3, 5], [2, 4, 6] ]
print(len(matrix)) #len() will return 2 print(len(matrix[1])) #len() will return 3

7 Looping! matrix = [ [1, 5, 9], [2, 4, 6], [8, 5, 3] ] for r in range(3): #iterate through each row index for c in range(3): #iterate through each col index print(matrix[r][c]) #access the specific element


Download ppt "2-Dimensional Lists (Matrices) in Python"

Similar presentations


Ads by Google