




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The lecture notes for cpsc 121 (computer science principles) class held in fall 2012. The notes cover myro functions, basic list operations, list functions, and the use of for loops. The document also includes exercises for practicing these concepts.
Typology: Study notes
1 / 8
This page cannot be seen from the preview
Don't miss anything!





Today ...
Reading
HW
The len function returns the length of a list
len([10, 20, 30]) 3 empty = [] len(empty) 0 The append function adds an element to the end of a list empty.append(10) print(empty) [10] empty.append(20) print(empty) [10, 20]
The remove function removes the first matching value in a list
empty.remove(10) print(empty) [20]
The del keyword deletes an element at a given index (subscript)
del empty[0] print(empty) []
The reverse function reverses a list
the list = ["spam", "ham", "eggs"] the list.reverse() print(the list) ["eggs", "ham", "spam"]
More on indexing
my_list = [6, 7, 9] Q: What is the length of the list? Q: What function do we call to get the length ... len() list_length = len(my_list) print(list_length) 3
Q: What is the index of the first list element?
my_list = [6, 7, 9] elem = my_list[0] print(elem) 6
Q: What happens if we give an index outside of 0 to length - 1?
elem = my_list[3] IndexError: list index out of range elem = my_list[-1] # a special case! print(elem) 9 elem = my_list[-4] IndexError: list index out of range
Iteration (looping) allows us to repeat blocks of code For example, instead of writing: the list = ["spam", "ham", "eggs"] print(the list[0]) print(the list[1]) print(the list[2])
We can use a for statement: for v in the list: print(v)