CS 111 w20 lecture 10 outline
1 Debugging word_check.py
continued
2 Tuples
- list: sequence of arbitrary elements, elements can be added, removed, overwritten (mutable)
- string: sequence of characters (single letters or symbols), elements are fixed (immutable)
- tuple: sequence of arbitrary elements, elements are fixed (immutable)
a_list = ["a", "b", "c"]
a_str = "abc"
a_tuple = ("a", "b", "c")
- tuples can do everything lists can do except item assignment
- Why?
- efficiency (technical reasons are beyond the scope of this course)
- safety
- for example, if you are representing locations in latitude and longitude, this data should always come in pairs
- Why?
3 Scope
3.1 Mystery
x = 5 def square(x): x = x * x return x y = 10 print(square(y)) print(y) print(x)
what if we remove x = 5
?
3.2 The scope of a variable refers to the part of a program where that variable exists
3.2.1 Practice
def cube(x): x2 = x * x x = x2 * x return x for num in range(4): if x % 2 == 0: x = cube(num) print(x) print(num) print(x) print(x2)
Need to add initial value for x
4 Aliasing
4.1 Mysteries
vec = [5,5,5] q = vec q[1] = 7 print(vec)
vec = [5, 5, 5] q = vec vec = [1, 2, 3] print(q)
def zero(vec): for i in range(len(vec)): vec[i] = 0 vec = [1,2,3] print(zero(vec))
- looking at these examples with pythontutor.com, we can see that the immediate value of a list variable in memory is an arrow to the actual list
- when we assign a new variable to a list or give a list as input to a function, it's this arrow that is used
4.2 Deep dive
name = "Aaron" first_name = "Aaron" print("name", id(name)) print("first_name", id(first_name)) print("Aaron", id("Aaron")) print() name = name + "!" print(name, id(name)) print(first_name, id(first_name)) print() print("mutable example:") ys = [1, 2, 3] xs = [1, 2, 3] print("ys", id(ys)) print("xs", id(xs)) ys.append(5) print("ys", ys, id(ys)) print("xs", xs) zs = ys print("zs", id(zs)) print() def append10(nums): print("nums", id(nums)) nums.append(10) append10(ys) print("ys", ys, id(ys)) print() def addfun(s): print("s", s, id(s)) s += "!" print("s", s, id(s)) course = "111" print("course", course, id(course)) addfun(course) print("course", course, id(course))