Docsity

CPSC 121 (Fall 2012) Lecture Notes - Lists, Study notes of Computer Science

Partial preview of the text

Download CPSC 121 (Fall 2012) Lecture Notes - Lists and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Lists

Reading

  • Ch. 14: pp. 76–

HW

  • HW 5 out

Reminders

  • No Class Friday

Warm up exercise

Consider this code snippet z = 10 def f(x, y, z): tmp = x + y // z return tmp What is the result of the following statements?

  1. f(20, 30) (a) 5 (b) 5. (c) 23 (d) None of the above
  2. f(40, 20, 10) (a) 42 (b) 42. (c) 6 (d) None of the above
  3. f(40, 20, 30) print("tmp =", tmp, "z = ", z)

(a) tmp = 40 z = 30 is printed (b) tmp = 40 z = 10 is printed (c) Syntax error (d) None of the above

Lists are mutable (can be modified)

The index (aka subscript) operator

listvar[index]

  • Each element in a list has an index (an int)
  • Indexes start at 0 and go to length - 1
  • Similar to how minutes go from 0-59 (with 60 minutes in an hour)

the list = [10, 20, 30]

first elem = the list[0] print(first elem)

10

the_list

Subscripts can be used to change list values

the list[0] = 15

print(the list)

[15, 20, 30]

the_list

  • Note the subscript operator is on the left side of the assignment!

The type of a list ...

the_list = [2, 4, 6] type(the_list) <class ’list’>

the_list = [’s’, ’p’, ’a’, ’m’] type(the_list) <class ’list’>