📜 ⬆️ ⬇️

Explanation of a Python task with a job interview

Salute, habrovchane! In anticipation of the launch of a new stream on the course “Web-developer in Python” we want to share a new useful translation. Go!



Having gone to several interviews again and having passed test tasks, I noticed that 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 fairly obvious, but the result of the execution of the third line f(3) did not seem to me so unambiguous. Let's see what happens after the initialization of the function f . To run this code, I will use IPython .

 >>> f <function __main__.f(x, l=[])> >>> f.__defaults__ ([],) 


The empty list that we see from the output of f.__defaults__ is the variable l in the function code.

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


Nothing special.

 >>> f <function __main__.f(x, l=[0, 1])> >>> f.__defaults__ ([0, 1],) 


But! Now we see that the variable l has the value [0, 1] due to the variability of the list object in Python and passing the function arguments as a reference.

 >>> f(3, [0, 1, 2]) [0, 1, 2, 0, 1, 4] >>> f <function __main__.f(x, l=[0, 1])> 


Also nothing special. Simply passing the list object as a variable l .

 >>> f(3) [0, 1, 0, 1, 4] >>> f <function __main__.f(x, l=[0, 1, 0, 1, 4])> 


And now the most interesting. When you run f(3) , Python does not use an empty list that is defined in the function code, it uses the variable l with 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 of '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 disassembled one of the most popular test tasks at the interview. This post is intended to show that you can not always rely on your intuition, however, like me on your :-).

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

Source: https://habr.com/ru/post/459518/


All Articles