Can you solve these 3 (seemingly) easy Python problems?

The solution can surprise you.

Lady Pythonista
Level Up Coding
Published in
5 min readJun 2, 2020

--

Image by FreePhotosART from Pixabay

Try to solve the following problems, then check the answers below.

Tip: All the problems have something in common so checking the solution to the first one before solving the remaining ones can lessen the challenge.

Problem 1

Imagine we have a couple of variables:

x = 1
y = 2
l = [x, y]
x += 5
a = [1]
b = [2]
s = [a, b]
a.append(5)

What will printing of l and s result in?

Jump to solution

Problem 2

Let’s define a simple function:

def f(x, s=set()):
s.add(x)
print(s)

What will happen if you call:

>>f(7)
>>f(6, {4, 5})
>>f(2)

?

Jump to solution

Problem 3

Let’s define three simple functions:

def f():
l = [1]
def inner(x):
l.extend([x])
return l
return inner
def g():
y = 1
def inner(x):
y += x
return y
return inner
def h():
l = [1]
def inner(x):
l += [x]
return l
return inner

What will be the result of the following commands?

>>f_inner = f()
>>print(f_inner(2))
>>g_inner = g()
>>print(g_inner(2))
>>h_inner = h()
>>print(h_inner(2))

Jump to solution

How confident are you in your answers? Let’s see if you were right.

Solution to problem 1

>>print(l)
[1, 2]
>>print(s)
[[1, 5], [2]]

Why does the second list react to the alteration of its first element a.append(5), but the first list completely ignores a similar change x+=5?

Solution to problem 2

Let’s see what happens:

>>f(7)
{7}
>>f(6, {4, 5})
{4, 5, 6}

--

--