Python Interview Questions

To succeed in IT, not only do you have to master the art of undergoing interviews, but also the art of giving them. As a competent Python developer, you must be able to answer all interview questions with authority and lucidity. As a recruiter, you must be able to formulate a comprehensive list of questions, pertinent to the job description. Don’t expect a fresh grad to paint you a holistic picture of your prospective system’s architecture, and don’t gauge the wisdom of a system architect by asking them about syntax.

Python is a beautiful and sleek language, with stable, scalable, and renowned frameworks like Django, Flask, and Pyramid, used by a constantly growing community. Let’s take a look at some of the questions that will help you touch all of its (or the most important) bases during a recruiter interview:

1 – Briefly explain the execution process of a Python file?

Answer:

Python is an interpreted language. The Python interpreter, behind the scenes, converts your source code into bytecode (.pyc files), and then executes them for you.

Red Flags:

  1. Not sure about the difference between compilation and interpretation.
  2. No knowledge of .pyc files and/or their difference from .py files.

2 – We know that Python is an object-oriented language, but does it have access specifiers?

Answer:

No. Python is a modern object-oriented language which considers the use of access specifiers (like private and public in C++) as primitive and redundant.

Red Flags:

  1. Don’t know what access specifiers are.

3 – How does the ternary operator work in Python? Can you assign a value to a variable within a ternary operator?

Answer:

The order of arguments in Python’s ternary operator is different from that in most languages, where you write the condition first, followed by the two expressions. In Python, you have to write it like: A if condition else B.

The execution is short-circuited in a way that only A is evaluated if the condition is true, and only B is executed, in case it’s false.

For the second part: No, assignments or statements (e.g. pass) can’t be used within a ternary operator.

Red Flags:

  1. “Yes” to the second part of the question.

4 – Can you explain how an exception can be caught in a Python program?

Answer:

By surrounding your code between try and except keywords. You can either use Python’s built-in exceptions or define a new exception class. You can also raise an exception in a specific case using the raise keyword.

Red Flags:

  1. No mention of the try and except keywords.

5 – How would you test Python code?

Answer:

Python has some cool modules to write testcases like unittest and Doctest which come bundled up with the Python standard library. You can also use tools like py.test, Hypothesis, mock, tox, and Unittest2.

Red Flags:

  1. Failure to mention at-least 2-3 names from the aforementioned.

6 – What are Python blocks and how do you define them?

Answer:

Python source code is organized by defining blocks via indentation. Blocks can have blocks within them and can be part of bigger blocks themselves.

Red Flags:

  1. No emphasis on the significance of indentation.


7 – If you have to choose between a list, set, and a dictionary to store 10 million integers, what will you use? Bear in mind that you would later like to query the frequency of a number within the dataset.  

Answer:

Since we have to cater for multiple occurrences of a number, we can’t choose a set, since it doesn’t store duplicates by design.

To find the frequency of a number within a list, you will have to iterate it completely, resulting in an O(n) complexity for searching, which is inefficient.

A dictionary, however, lets you store key-value pairs. You can store a number as the key and the amount of times it has been stored, as the value. This way, whenever you want to query the frequency, you can get the result in O(1). This makes a dictionary the best choice in this particular scenario.

Red Flags:

  1. Chooses set.
  2. Doesn’t explain the basic storing and querying processes associated with each datatype.

8 – Please list a few differences between lists and tuples in Python.

Answer:

Python lists are mutable, whereas Tuples can’t be edited.

Tuples can be defined with a list of comma-separated integers with or without parenthesis. On the other hand, lists are defined via square brackets or using the list constructor.

Red Flags:

  1. No mention of the mutability difference.

9 – When should you use shallow copy instead of deep copy, and vice versa?

Answer:

When you make a shallow copy, a new object gets created and it keeps the reference pointers of the original object. As the shallow copy process is not recursive, copies of the original child objects are not created. So basically, what you have is two objects that share the same set of elements. This means that any changes made in the copied object instantly get reflected in the original object.

In case of a deep copy however, a recursive copy process is carried out, and copies of all child objects are created. So, if you make a change in the copied object, they won’t get reflected in the original object.

When and why you should choose one over the other depends on the use-case, but it’s paramount that you understand the internal working of the two processes.

Red Flags:

  1. Can’t coherently explain how the memory for both the copies is managed.

10 – What are list comprehensions and why do we use them, if at all?

Answer:

List comprehensions provide a great way to define lists where every element actually results from an operation being performed on every member of another list or a sequence. For example, if you want to store a list of squares of the first 10 prime numbers, you can use list comprehension to do so. However, list comprehensions shouldn’t be used for trivial iterations like printing values etc. Only use them if you want to build a resultant list which contains the updated values.

Red Flags:

  1. Failure to point out when and when not to use list comprehensions.

11 – What do you know about the global interpreter lock?

Answer:

The Global Interpreter Lock, aka GIL, is a mutex that prevents multiple thread to execute Python bytecode simultaneously. This lock is necessary because the memory management in CPython isn’t thread-safe. This may prevent multi-threaded applications to use multiple CPUs and is therefore a bottleneck. However, not all the operations are concerned by the GIL, such as the IO operations or some computation done within libraries (e.g. numpy).

Red Flags:

  1. Never heard of it.

12 – Is None or == None, what should you use, and why? Is there a difference between == and is operators?

Answer:

Yes, there is a difference between == and is. The former checks for equivalence and the latter checks whether the two specified objects are actually the same.

However, with that said, in the case of None, there is no difference between the two. Why? Because there is only one None object.

As a rule of thumb, using Is None is the way to go.

Red Flags:

  1. Fails to mention any of the three pointers above.

13 – What would the output of this code be?

1
2
3
4
5
6
7
8
def f(a,list=[]):
    for i in range(a):
        list.append(i*i)
    print(list)
 
f(3)
f(2,[1,2,3])
f(2)
[0, 1, 4] [1,2,3,0,1] [0, 1, 4, 0,1]

The key thing to remember here is that the list object is only created once, when the function is defined. In the first and third call, the list object is the same. However, during the second call, we used another object for the list argument.

Red Flags:

  1. Didn’t know that the default value of the argument “list” was created only once.

14 – In a function, what is the meaning of *args and **kwargs?

Answer:

The single asterisk *args is used in a function definition when you are not sure how many arguments you might have to pass to a certain function.

The double asterisk **kwargs allows you to send keyworded arguments to a function, which can contain as many arguments as you please.

Red Flags:

  1. Doesn’t mention the difference between the two.

15 – What would the output of this code be?

1
2
list = ['1', ‘2', '3', '4', '5']
print (list[12:])

Answer:  The output would be [] and not an index error. This is because we are trying to retrieve the slice and only specifying the starting index.

Red Flags:

  1. Any errors.

16 – Please point out a few differences between Python 2.x and 3.x?

Answer:

There are more changes/updates in Python 3 than can be mentioned, but here are the most commonly known ones:

  1. Change in the printing syntax.
  2. Change in the way integer division behaves. E.g. 3/2 = 1 in Python 2 as opposed to 1.5 in Python 3.
  3. Introduction of Unicode and two byte classes.
  4. A new method “__contains__” for range object, which helps fasten the lookup process.
  5. Enforcement of the new syntax to raise exceptions; i.e. you will get an error if you don’t surround the exception argument with parentheses.
  6. Deprecation of the .next() method. Only the next function remains.
  7. A TypeError is now rightly raised whenever two unorderable types are compared.

Red Flags:

  1. Failure to identify at-least 3,4 differences between the two versions (especially if you are interviewing for an experienced resource).

17 – What are some reasons to dislike Python?

Answer:

This question is important because it makes the applicant think. There is no unanimity regarding the answers, but a cognizant, unbiased and experienced Python developer will always have something to say. If Python has ever really made a person pull their hair out, they would be able to vehemently explain what they don’t like (or understand that some people may not like) about the language to you.

Here are a few examples of topics that could be raised by the applicant:

  1. Having to deal with Python 2 compatibility whereas version 3 have been released more than 10 years ago.
  2. The usage of whitespace to define blocks.
  3. GIL.
  4. Dynamic typing.

Red Flags:

  1. “Nothing that comes to mind”.

 

Final Word

This list included a collection of easy, tricky, and difficult questions. Hence, it should allow you to assess the experience level of most candidates astutely. Again, don’t make the final call based on a person’s lack of familiarity with trivial stuff like certain language limitations or syntax, as they are not hard to learn. What you need to figure out is whether or not they are capable of knowing right from wrong, when writing (or designing) code for your application. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment.

Ready to see CodinGame

Assessment in action?

Shopping Basket