Advanced Python Interview Questions

Introduction

Today I’m going to discuss with you Advanced Python Interview questions that you can use in your interviews or come back here to practice and try to remember. This will be an ever growing guide but at the same time I will try to be selective. I do not want to put material here that’s repeated a lot on other sources. Most of the content will be unique and catchy so you can outwit yourself or interviewees!

Over the course of the last 23 years of being a developer, manager, architect and systems engineer I have had to interview over 250 people. In most of the roles I was in the main programming language and environment was Python. The useage varied from server-side code, graphics applications, machine learning and just general scripting. One thing that I learned is good knowledge of the fundamentals is what makes the difference between an average programmer and a good one.

I always try to stick to the fundamentals when I’m interviewing someone. Also after a while you start seeing patterns in the interview process. Certain characteristics of people come out quickly for example if someone is a problem solver, an over-analyzer, the person that just wants to write code etc. In this article I’m going to try to break down some specific questions regarding Python. These will not be in general nature problem solving tasks such as those found in websites such as leetcode. As side note you should be practising in leetcode if you want to be able to do well in logarithmic problems.

As part of this blog I have uploaded all the code in the git repository which includes references to everything seen below. If something is missing please reach out to me and I will make sure to include it. You can find the git repo for it here.

Advanced Python Interview Questions
Advanced Python Interview Questions

Questions

How does Python Inheritance work

The following items need to be demonstrated for the code below:

  • Be able to explain the method order of the class inheritance
  • How functions get affected if they have the same name
  • Be able to explain what output the below program will have
class Base1: 
    def __init__(self) -> None: 
        print ('This is base1 init') 
    def which_one_executes(self): 
        print ('Base1 execution') 

class Base2: 
    def __init__(self) -> None: 
        print ('This is base2 init') 
        def which_one_executes(self):
            print ('Base2 execution') 

class Main(Base1, Base2): 
    def __init__(self) -> None: 
        super().__init__() 
        print ('This is main') 
        self.which_one_executes() 

main_obj = Main()
The method reverse order in Python works from right to left, which means the left most class as defined in our case above Base1 will supersede everything else that's defined past after it. So in the case below we will be seeing the print out of the Base1 class along with the Base1 class function execution as they are both taking precedence in the method execution order in the class declaration.
main alex@DYNAMH ~/code/unbiased-coder/python-interview-questions > python ./mro.py
This is base1 init
This is main
Base1 execution
The reason that we are only seeing the base1 output is because python relies on what is called the method resolution order which means the left most class takes priority in the inheritance order of the methods. In this case that class is Base1 which is why we are seeing the output of it being executed.

What is the difference of an anonymous function and a tuple in Python

Things that need to be demonstrated here are as follows:

  • Understand what an anonymous Python function is
  • Understand what a set is and how it’s declared
  • Be able to provide an explanation of how each can be initialized using the the set() or lambda declaration (bonus question)
  • Be able to guess the output of the print out functions
example1 = (1) 
example2 = (1,) 
print ('Example1: ', example1, type(example1))
print ('Example2: ', example2, type(example2))
The answer here is that the first one is an anonymous function which takes the argument of 1 and returns that number and the second one is a set with only 1 element in it. The comma separator is what changes the declarative in the code above and makes it more difficult to discern between the two. If we were to execute the code above we will see the following output:
main alex@DYNAMH ~/code/unbiased-coder/python-interview-questions > python ./tuple_anon_func.py
Example1:  1 
Example2:  (1,) 
The reason the first execution returns an integer is that by default function takes the brackets around number 1 as an anonymous function which returns just that as an integer. In the second case it sets it as a tuple because the comma separator defines it as such.

What does the following Python Lambda expression return

In this example you will be presented with a dynamic lambda expression and the expectation is to guess the output of what it will be showing if the code gets executed.

The interviewee should successfully demonstrate the following things:

  • Explain why the result was the value derived
  • What does an anonymous lambda python casting do
  • How does python treat Booleans in arithmetic
(lambda x,y,z: x+y+z)(1,2,3)-True+False
The answer is 5 the reasoning is as follows:
  • When doing Boolean arithmetic the Booleans are converted using int so False would be 0 and True will be 1
  • The lambda brackets allows you to supply arguments on the fly when executing as a one-liner
  • The evaluation of the lambda result is 6 since it's a simple addition and the Booleans and the values shown above so only True affects the operation

What does the Sum function return when executed

In this example you will be presented with some sample code of the sum function being called. Your task is to say what the output is going to be:

Some things you need to explain are:

  • How you came to the conclusion of the expected output
  • What happens when the sum function is being called internally with Python
sum = 1
sum += sum([1,2,3,4,5])
print ('The sum is: ', sum)
The answer here is that the code is invalid and will raise an exception of type: TypeError The reason this is happening is that function casts the name sum into an integer which replaces in the current executing context the sum function. So the output would be:
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'int' object is not callable
The right thing would be not to use a predefined namespace function name for your variables or if you have to use them for whatever reason you can call the del function to clear it out from the running executing context.

Write a Fibonacci Function using a one-liner using lambda

Things that need to be demonstrated here:

  • Code should be 1 line the reason for this is to show conditional expression matching in the same line
  • The use of a lambda function could be leveraged to accomplish this
  • The use of function recursion needs to be demonstrated here
The code below demonstrates all of the requirements mentioned above.
  • The use of recursion exists as we call ourselves and by ourselves I mean the lambda function
  • The use of conditional expressions is being made as a one-liner which demonstrates the ability to do that quickly
fib = lambda limit: limit if limit < 2 else fib(limit-1) + fib(limit-2) 
print ('Fib(20): ', fib(20))
print ('Fib(10): ', fib(10))
If we were to execute the above code we should be able to see the Fib series for the result of 10 and 20:
main alex@DYNAMH ~/code/unbiased-coder/python-interview-questions > python ./fib.py
Fib(20):  6765
Fib(10):  55
This is the correct output if you were to calculate the Fib for 20 and 10 you should be getting the equivalents as shown above. An often overlooked thing is that you can have a lambda call itself recursively this works quite well but may be slower due to how Python works under the scenes in regards to the stack frames. Always prefer to write a normal function over the syntax above this is just for fun and checking the strength of the candidates skill level.

What is the difference between a classmethod and a staticmethod in Python

The interviewee needs to demonstrate a good understanding between the two concepts which are not very common in Python programming along the things below:

  • Explain where classmethods are being used
  • Explain the difference between the two
  • Explain where staticmethods are being used
  • Explain what is the advantage of not instantiating a class object and calling into routines directly
To better demonstrate this we need to write some example code and break it down by pieces on what each part does.
class TestClass(object):
    def __init__(self) -> None:
        super().__init__()

    @classmethod
    def test_class_method(cls):
        print ('this is a class method')
        print ('instance is: ', cls)

    @staticmethod
    def test_static_method():
        print ('this is a static method')
        print ('static methods have no instances')

    def test_regular_method(self):
        print ('this is a regular method')
        print ('instance is: ', self)

TestClass.test_static_method()
TestClass.test_class_method()

try:
    TestClass.test_regular_method()
except TypeError:
    print ('Failed executing regular method, regular methods need an instance to be executed')

t = TestClass()
t.test_regular_method()
The code above demonstrates three scenarios which the interviewee needs to explain:
  • What happens with a regular class function
  • What happens with a classmethod decorated function
  • What happens with a staticmethod decorated function
In all three cases above lets see what the output is when we execute the code and see if it's what we are expecting:
main alex@DYNAMH ~/code/unbiased-coder/python-interview-questions > python ./difference_class_static_method.py
this is a static method
static methods have no instances
this is a class method
instance is:  
Failed executing regular method, regular methods need an instance to be executed
this is a regular method
instance is:  <__main__.TestClass object at 0x6fffffe9af10>
Lets start going through this piece by piece. The first part to understand which is the easiest is that the regular method requires an instantiated class object in order to be executed as it only accepts as a first argument the self (class instantiated object). So when we try to execute it directly from our Class definition it will fail and raise the exception error of TypeError. Now that we have this out of the way lets focus on the static method which is also a simple one, this is generally used when you want to make a function to be executed as part of your class module without requiring to instantiate an object for it. The advantage of course is that this can be used directly inside the code without having much memory impact and relying on an object. Furthermore it can be used in a static context where we just need to import the class in the beginning of our code so any dependencies the class may have like inheriting other classes etc or running specific init functions do not matter.

Conclusion

If you are looking to hire someone please consider a holistic approach. Assemble a proper list of questions ahead of time and just include those are bonus tips to see how well he performs. Not everyone needs to score super high and not everyone needs to be proficient in every little detail a language has. A common problem is that a lot of interviewers get caught out on scoring but miss a lot on how the person is thinking and analyzing a problem. Some solutions which can easily be google’d don’t need to weigh heavily on your decision of whether or not to hire a candidate. Do you have any other interesting questions to offer to me please put in the comments below I’d be interested to hear about them and update my guide. Did I make any mistakes please let me know about that too!

Python interview questions can be really easy and really complex this guide was meant for those looking to push their limits.

If you are looking on some more information on Python in general I have a section of articles here.

Some common ones that you may enjoy can be found here:

Leave a Comment

Your email address will not be published. Required fields are marked *