Computer Programming
ENEE 101
Lec#17 (Sequences part 3)
Department of Electrical and Electronic Engineering
University of Jeddah 1
Copying lists
Wrong way: list2 = list1
This part of
memory is
marked as
free
Proper ways:
2
Passing lists to functions 1/3
Example
Lists are mutable objects (like all objects). Simple variables are not mutable.
Output
3
Passing lists to functions 2/3
Output
lst is created to make list1
lst is updated to make list2
A new list is created to make list3
lst is updated to created list4
lst remains in memory although is not accessible outside the function add.
list1, list2, list4 will share the same id which is the id of lst. 4
Passing lists to functions 3/3
Problem solved
Output
list1, list2, list4 will differ and have different ids.
5
Returning a list
Initialization
required
As we know for
variables
list2 is:
[6, 5, 4, 3, 2, 1]
6
Multidimensional lists - Intro
A nested list (a list of lists)
7
Two-dimensional lists
A two-dimensional list, called matrix, can be seen as a list of rows
and each row is a list.
A matrix is addressed with row and column indexes: matrix [ i ][ j ]
8
Create and print a matrix
This example creates the matrix row by row:
You can also print a matrix directly print(matrix).
There are other ways to print a matrix:
Same output
123
456
789
123
456
789
9
Operation Examples
sum of all elements
sum per columns
Find the largest
sum row
10
Sorting Example
• This is sorting of a list containing lists (pairs of values, i.e.,
coordinates)
• The contained lists are treated as elements.
11