Lesson 1 exercises

Exercise 1.1

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

Exercise 1.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 1.3

Do this before Exercise 1.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 1.4

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

Exercise 1.5 (optional)

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