Lesson 3 exercises

Because your GitHub teams are not yet assembled, for these exercises, submit your responses via email written to all seven of the course staff.


Exercise 3.1

Describe in words the difference between a mutable and immutable object.

Exercise 3.2

a) Describe in words the difference between the == operator and the is operator.

b) Why should you not use the == operator to compare two floats?

Exercise 3.3

Do this before Exercise 3.4. Without running the code, write what will be printed for the following Python codes.

a)

my_list = [1, 2, 3]
my_list[2] = "four"

print(my_list)

b)

a = 5
b = 2
a = b

print(a, b)

c)

def first_element_103(x):
    x[0] = 103

x = [1, 2, 3]

first_element_103(x)

print(x)

d)

def add_103(x):
    x += 103

x = 4

add_103(x)

print(x)

e)

def add_103(x):
    return x + 103

x = 4

x = add_103(x)

print(x)

f)

def append_103(x):
    x.append(103)

a = [1, 2, 3]
b = a

append_103(b)

print(a)

g)

add_three_numbers = lambda x, y, z: x + y + z

print(add_three_numbers(*(5, 6, 7)))

h)

print([i for i in range(1, 10) if i % 2])

i) As we will learn when we learn about style, you should not write code like this example; it’s overly tricky to read. But it will help see if you understand how list comprehensions work.

print([i if i % 3 == 0 else i**2 for i in range(1, 10) if i % 2])

j) This one is tricky. Don’t worry if you have trouble with this.

def append_103(x=[]):
    x.append(103)

    return x

append_103()
append_103()
append_103()

print(append_103())

Exercise 3.4

Check your work from Exercise 3.3 by running the codes in code cells. Do not change your answers to Exercise 3.3 after doing this.

Exercise 3.5

What is the difference between a key and a value in a dictionary?

Exercise 3.6

Can a dictionary have duplicate keys? Can it have duplicate values?

Exercise 3.7 (optional)

Write down any questions or points of confusion that you have.