Python task explanation with job interviews

Original author: Artem Rys
  • Transfer
Salute, Khabrovites! In anticipation of the launch of a new thread on the course "Web-developer in Python" we want to share a new useful translation. Go!



Having gone to several interviews again and passed the test tasks, I noticed that the interviewers like tasks like the following.

def f(x, l=[]):
    for i in range(x):
        l.append(i * i)
    return l
>>> f(2)
>>> f(3, [0, 1, 2])
>>> f(3)


Question: What will this code output?

The output of the first two lines is quite obvious, but the result of the third line f(3)did not seem so straightforward to me. Let's see what happens after the function is initialized f. To run this code, I will use IPython .

>>> f

>>> f.__defaults__
([],)


The empty list that we see from the execution result f.__defaults__is a variable lin the function code.

>>> f(2)
[0, 1]


Nothing special.

>>> f

>>> f.__defaults__
([0, 1],)


However! Now we see that the variable lhas a value [0, 1]in virtue of the variability in Python list object and the transfer function arguments by reference.

>>> f(3, [0, 1, 2])
[0, 1, 2, 0, 1, 4]
>>> f


Nothing special either. Just passing an object listas a variable l.

>>> f(3)
[0, 1, 0, 1, 4]
>>> f


And now the most interesting. When you start f(3), Python does not use the empty list that is defined in the function code, it uses a variable lwith values ​​from f.__defaults__ ([0, 1]).

PS

If you need a function that uses an empty list after each call, you should use something like this (set the value ‘l’to ‘None’).

def f(x, l=None):
    if l is None:
        l = []
    for i in range(x):
        l.append(i * i)
    return l
>>> f(2)
[0, 1]
>>> f(3, [0, 1, 2])
[0, 1, 2, 0, 1, 4]
>>> f(3)
[0, 1, 4]


Conclusion


So I made out one of the most popular test tasks for an interview. This post is intended to show that you can not always rely on your intuition, however, as I do on my own :-).

We hope this translation will be useful to you. Traditionally, we are waiting for comments and see you on the course .

Also popular now: