Download presentation
Presentation is loading. Please wait.
1
Introduction to Computer Science
Programming with Python
2
2D Arrays / List of Lists
3
List of Lists A list in Python can contain multiple lists
A list of lists in other programming languages is known as 2D Array/List It is very useful to store Matrix-like data such as graphs, charts, etc 2 Dimensional Array
4
List of Lists We can define list of lists as follows
Or more human readable a = [[1, 2, 3], [4, 5, 6]] a = [ [1, 2, 3], [4, 5, 6] ] Row 0 Row 1 column 1 column 2 column 3
5
A 2-Dimensional Array
6
Length of Rows and Columns
It is possible to get how many rows and columns of the Matrix or list of lists using the len function length of a: 2 (number of rows / lists) 3 columns in row 0 a = [ [1, 2, 3], [4, 5, 6] ] print("length of a: ", len(a)) print(len(a[0]), " columns in row 0")
7
The append() function with 2D Lists
Just like lists, we can use the append function to insert data to the list We can add to an existing list. In other words, add a column to an existing row or add a new row Remember, lists are mutable so list of lists are also mutable add 100 to row 0 – this will increate the length of row This will add a new row to the list This will add a number without a list - do not do it Instead, add a single value in a row itself / list of 1 value a[0].append(100) a.append([120,200,320]) a.append(100) a.append([100])
8
Definite Loops with 2D Lists / List of Lists
It is possible to loop through 2D array using the classic way that works with all programming languages. This is good because it will give you an insight of how to deal with 2 Dimensional Lists/Arrays Nested for loops First loop will go through rows Second loop will go through each column of the row. Or, each element in a specific row
9
Definite Loops with 2D Lists / List of Lists
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9, 0] ] for row in range(0, len(a)): for col in range(0, len(a[row])): print(a[row][col], end="\t") print()
10
Definite Loops with 2D Lists / List of Lists
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9, 0] ] ? print("element of a[2][3]")
11
Definite Loops with 2D Lists / List of Lists
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9, 0] ] print("element of a[2][3]")
12
Definite Loops with 2D Lists / List of Lists
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9, 0] ] Debugging table consists of 10 rows (excluding header) Row Col a[row][col] / value for row in range(0, len(a)): for col in range(0, len(a[row])): print(a[row][col], end="\t") print()
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.