Potential Python Interview Questions

Andrei Neagoie
Andrei Neagoie
hero image

Are you about to sit for a coding interview with a company that uses Python?

Not sure what questions they might ask you?

Chances are high that if this is your first time interviewing, you might be thinking that they’re going to ask you a bunch of specific questions about Python and test your knowledge of it right?

Seems obvious

Well, you would be wrong, but it’s not your fault that you might think this.

All it takes is a quick Google search on the topic of ‘Python interview questions’ and you’ll see heaps of articles with “150 Python interview questions that you need to know right now, to get the job”...

No joke, over 100,000 people search for these types of specific language interview questions every month, but the reality is, it’s actually incredibly rare that the interviewer will ever ask you any broad questions about the particular language or framework you're interviewing with.

Sure, they might ask you a specific language question if it directly ties into a problem that they’re working on or affects an answer that you gave to a technical question, but this is usually the only time they would do this.

Asking you a background question about how Python works without it tying into solving a specific problem with Python, is similar to sitting your driving test and being asked who invented the car and how an engine works, instead of seeing if you can drive.

When the tester asks the wrong questions

99.9% of technical coding interviews are run by a member of the programming team, and feature:

  • A quick hello
  • Followed by a series of technical questions that you’ll need to solve using a specific language or framework, in this case, Python
  • And then some final personal questions

This is pretty much the same format for every coding interview, regardless of language or company size, and it’s why we cover how to solve these technical questions using any language in this article here.

Cracking the coding interview process

Most companies believe that if you can solve the technical problems using Python, then it’s proof enough that you already know what you need to know about the language. That and the fact that during the interview, you’ll discuss your solutions to the problems and any strengths and weaknesses of your approach. i.e maybe there’s a solution you’ve found but it’s flawed if you use it in a certain way, simply due to limitations in Pythons code.

If you’re stuck for time and want to prepare for your coding interview effectively, I highly recommend you follow that guide and spend your time there instead.

So what’s the point of this guide?

2 things:

1️. Test your knowledge!

Ideally, you already know all this information from when you learned to code with Python, but treat it as a little bonus knowledge to add to your skill set or to perhaps recap if you learned Python a while back.

2️. Be prepared for non-tech interviewers

It sucks but sometimes the person interviewing isn't a programmer.

What does this mean and why does it matter?

Well, in very large companies, they sometimes outsource pre-liminary interviews to people with little to no programming knowledge. So instead of a team lead asking you abou tyour experience with the language and how it might fit a task they do, you have to answer some random questions instead...

Not great right? Even worse is that will have a specific answer that they're looking for.

Ideally they should filter this out with an automated quiz or something before you ever get this far, but it does happen so it's worth knowing this stuff just in case. This way, if you’re in the 0.1% of interviews that do ask you specific Python interview questions, you’ll be able to answer the most important ones and still get the job.

Alright, with that out of the way, let’s get into these potential python interview questions…

What type of language is Python?

Python is a high-level, interpreted, general-purpose programming language that can be used to create a wide variety of projects when combined with the right tools and libraries. Although it can write scripts, it’s mainly used for general-purpose programming.

Being an interpreted language, Python doesn’t technically need to be compiled into machine code before it’s run. Instead, it’s translated to bytecode and then run through an interpreter.

What are the key features, benefits, and limitations of Python?

Quick to use. Being a high-level language, Python is easy to learn and you can write code quickly, thanks to its more user-friendly approach when compared to a low-level language. Just remember that Python is case-sensitive when writing your code.

Slow(ish) to run. Because the code runs through an interpreter first before it executes, it does add some minor bottlenecks to performance speed. You can get around this with C-based extensions though.

For example

Cython is a superset of Python, that can be used to speed up your Python scripts. It’s basically Python with C data types.

The extension takes the Python source code, and then translates it into optimized C/C++ code and compiled as Python extension modules. This allows for both very fast program execution and tight integration with external C libraries

Flexibility. Python is a platform-independent language which means it allows you to run the same source code on any platform like Windows, Linux, Mac, etc. However, make sure to double check the compatibility of your modules, as some modules could be OS specific

Ease of use. Python is dynamically typed which has both strengths and weaknesses. The main benefit is that you don't need to declare the type of variable while assigning a value to a variable.


def plustwo(x):

  return x + 2

def greet(name):

  return "hello " + name;```

Compare that to a statically typed language like C++

``` // C++  statically-typed language

int plustwo(int x){

  return x+2; 

}

string greet(string name){

  return "Helllooo " + name;

}

However, because of this, you can also open up your code to errors or bugs.

Can be used for OOP programming. Functions are first-class objects in Python, which means they can be assigned to variables or returned or passed into functions. It also allows the definition of classes, composition, and inheritance.

Compatibility. We already know that Python can be used in a wide variety of projects, but it’s also used as the ‘glue’ language to connect other languages and components.

Community. Thanks to all these benefits, there’s a large community of Python developers out there who can help out with any coding issues.

Opensource. Python is free to use and is always being updated, including its multiple libraries.

What is the difference between .py and .pyc files?

Remember how I said Python uses an interpreter to change files into bytecode so that it can execute it?

Well, the .py file is the original Python source code, while the .pyc file is that same code once it’s been converted into bytecode to be run.

What does the acronym PEP stand for?

PEP stands for Python Enhancement Proposal, and is a document used to help propose new features to Python. It’s worth keeping an eye on this if you want to stay up to date with new implementations or even understand the rationale behind each new implementation in Python.

What is PEP-8?

PEP-8 is the official style guidelines and recommendations for writing code in Python. Everything from naming convention advice and layout tips.

Is indentation required in Python?

Python uses indentation to specify a new block of code. This means that any functions, loops, and classes must all be inside that indented block, usually signified by 4 spaces.

Failure to do this will result in potential indentation errors in your code, as you can see below:

def hi():

print('hello')

# IndentationError: expected an indented block

How do you debug a Python program?

The easiest way to debug Python code is to install a debugger module such as pdb (python debugger).

What are functions in Python?

A function is a pre-created block of Python code that is executed when called.

# round is a built-in function

num = round(5.6)

print(num)

# user defined function

def multiplyTwo(n):

  return n*2

print(multiplyTwo(100))

You can have both built-in functions, and user-defined functions.

What are Python modules?

Modules are Python files (.py) that contain Python code and functions, which can be imported into another Python program.

For example

  • os
  • sys
  • math
  • random
  • data time
  • JSON

What are Python packages?

Python packages are simply namespaces that contain multiple modules.

What’s the difference between a module and a package in Python?

A module is a single Python file that you can import and reuse, while a package is a collection of modules.

What are the built-in data types of Python?

  • Numeric data types: int, float, complex
  • String data types: str
  • Sequence types: list, tuple, range
  • Binary types: bytes, bytearray, memoryview
  • Mapping data type: dict
  • Boolean type: bool
  • Set data types: set, frozenset

What are Python namespaces?

A namespace is a method of organizing and referencing objects in Python.

Put simply, when you create an object in Python, both the object's name and the location where the function is created are saved. The namespace is what maintains and saves that information, or deletes it when no longer needed.

There are 4 types of namespace in Python:

  1. Built-in
  2. Global
  3. Enclosing, and
  4. Local

What’s the difference between a list and a tuple?

Both lists and tuples are used for storing data, but the main difference is that lists are mutable objects i.e they can be edited, while tuples are immutable, meaning they can’t be edited.

Because lists are editable and more flexible, they usually take up a larger memory footprint, which can cause them to run slower. Tuples being fixed generally run faster.

Lists and tuples can appear very similar to beginners since both are compound objects that contain a sequence of elements and both can contain elements of different data types. However, while lists are mutable objects, tuples are immutable ones and this is the main difference between these two types.

Due to this fact, lists are usually slower and have a larger memory footprint but are far more flexible, while tuples are faster and lighter, being less flexible and immutable.

Finally, lists are declared with square brackets [1,2,3], whereas tuples are declared with round brackets (1,2,3).

What’s the difference between Python arrays and lists?

Both store data, but arrays are limited to single data type elements, whereas lists can hold any type.

import array

my_list = [5, 8, True,"hello"] # heterogeneous

# my_arr_wrong = array.array('i',[5,8,True,"hello"])  

# TypeError: an integer is required ( got type str)

my_arr = array.array('i',[7,8,9,10,11]) # homogeneous data

What are literals in Python?

Literals are simply notations for a fixed value in code. These can be:

  • Strings
  • Numeric
  • Boolean
  • Special literal = none
  • Collections = List, Tuple, Set, Dict

What are keywords in Python?

Keywords are specific, case-sensitive, reserved words saved inside of Python, that are used to define the syntax and structure of the Python language, and apply specific actions.

(You cannot use these words for anything other than their core function.)

There are currently 33 keywords in the current iteration of Python:

  • and
  • or
  • not
  • if
  • elif
  • else
  • for
  • while
  • break
  • finally
  • from
  • global
  • import
  • in
  • as
  • def
  • lambda
  • pass
  • return
  • true
  • false
  • try
  • with
  • assert
  • class
  • continue
  • del
  • except
  • is
  • none
  • nonlocal
  • raise
  • yield

What are * args and ** kwargs, and when would you use them?

The clue is in the name, arguments, and keyword arguments.

We use **kwargs when we are not sure how many keyword arguments are going to be passed to a function.

Whereas we use *args when we’re not sure how many arguments are going to be passed to a function, such as lists or tuples, etc.

def getInfo(**detail):

  #print(type(detail)) # <class 'dict'>

  for key, value in detail.items():

    print('{} is {}'.format(key, value))

getInfo(course="Complete Web Developer", instructor="Andrei",duration="40 hrs")

# *args

def multiplyNum(*numbers):

  #print(type(numbers)) # <class 'tuple'>

  result = 1

  for n in numbers:

    result*=n

  print(result)

multiplyNum(1,2,3) # 6

multiplyNum(4,5,8,9,10)  # 14400

What is the lambda function and why would you use it?

Lambda is an anonymous function. It can only have one expression but as many parameters as you want. It’s usually used when you need an anonymous function for a short time.

How does break, continue and pass work?

Pass is used when you want to call a block of code, but bypass its execution so that nothing happens from this code.

Continue allows you to skip a section of code when a particular condition is met.

Break allows a loop to terminate when a condition is met.

What is meant by pickling and unpickling, in Python?

Python offers a serialization module built in, to help store and then retrieve files for later use. Rather than just call it serialization, the name ‘pickling’ comes from the concept of creating something to be then used later, similar to pickling food into jars.

  • The pickle module accepts objects and converts them into strings to then be dumped into a file (pickle.dump)
  • The process of retrieving those stored objects is unpickling (pickle.load).

Is it safe to pickle and unpickle like this?

Yes and no. In theory, the process is safe, as long as you trust the code source that you are unpickling. The reason being is that the code can be set to execute on unpickling, which can cause issues if the code is malicious.

How is memory managed in Python?

There are 3 core things to understand when we talk about Python and its memory management:

  • Python uses a private heap space to store all objects and data structures. This is only accessible by the interpreter, not the programmer
  • Pythons memory manager regulates and allocates memory in this private heap, controlling sharing, caching, segmentation and allocation
  • Finally, Python has a built in ‘garbage collector’ which recycles the unused memory so that it can be better used by the private heap

The Garbage Collector works by looking for objects that have no references and then removing them. The logic is that if it’s not being used i.e referenced) then it’s not needed.

Why isn’t all the memory deallocated when Python exits?

If a module has a circular reference to another object or is being used by another object, then it is not de-allocated by the garbage collector.

What is the difference between deep and shallow copy?

Both are methods of copying an object, but the way they copy is the main difference.

A shallow copy will copy the object, but it also uses the same references as the original. Any changes to the original will then affect the shallow copy. The shallow copy method generally allows for faster execution of the program.

A deep copy is a new copy that is its own object and doesn’t reference the original. This means that if the original changes, the deep copy is not affected.

import copy

original_list = [{'name': 'Amy', 'luckyNum': 8}, {'name': 'Bob', 'luckyNum': 7}, {'name': 'Corgi', 'luckyNum': 100}]

shallow_copy = copy.copy(original_list) # shallow copy - copy the reference 

deep_copy = copy.deepcopy(original_list)

print('Before Update - original_list is: \n', original_list)  

original_list[2]['name'] = 'John'

original_list[1]['luckyNum'] = 999

print('After Update - original_list becomes: \n', original_list)

print('Shallow Copy is: \n', shallow_copy)

print('Deep Copy is: \n',deep_copy)

Then run the code:

Before Update - original_list is: 

 [{'name': 'Amy', 'luckyNum': 8}, {'name': 'Bob', 'luckyNum': 7}, {'name': 'Corgi', 'luckyNum': 100}]

After Update - original_list becomes: 

 [{'name': 'Amy', 'luckyNum': 8}, {'name': 'Bob', 'luckyNum': 999}, {'name': 'John', 'luckyNum': 100}]

Shallow Copy is: 

 [{'name': 'Amy', 'luckyNum': 8}, {'name': 'Bob', 'luckyNum': 999}, {'name': 'John', 'luckyNum': 100}]

Deep Copy is: 

 [{'name': 'Amy', 'luckyNum': 8}, {'name': 'Bob', 'luckyNum': 7}, {'name': 'Corgi', 'luckyNum': 100}]

How is multithreading achieved in Python, and should you use it?

Although you can technically install a multi-threading module in Python, I wouldn’t recommend it as it will slow down your code, mainly due to how Python works.

Python uses a Global Interpreter Lock (GIL) to execute threads. This means that when you try to run multi-threads, it alternates between each thread on a single CPU core, instead of running them concurrently. This then causes a delay in each thread's completion time as it pauses and jumps back and forth.

How did you do?

So there you have it: 25 potential python interview questions and their answers.

How well did you do? Did you know the answers to each question?

Don’t beat yourself up if you miss any. Like I said before, 99.9% of the time, the questions will almost always be more technically focused, but it's still worth keeping these broader language answers in mind, just in case.

By the way, if you want to learn both technical and non-technical skills that you need to have a successful career in the tech industry, then come join us as a member of Zero To Mastery.

More from Zero To Mastery

[Full Guide] Learn To Code For Free in 2024 & Get Hired in 5 Months (+ Have Fun Along The Way!) preview
Popular
[Full Guide] Learn To Code For Free in 2024 & Get Hired in 5 Months (+ Have Fun Along The Way!)

Updated for 2024 (including A.I. & ChatGPT). In 2014, I taught myself how to code & got hired in 5 months. This is the step-by-step guide I used. Now 1,000s of other people have also used it to learn to code for free & get hired as web developers.

How To Ace The Coding Interview preview
How To Ace The Coding Interview

Are you ready to apply for & land a coding job but not sure how? This coding interview guide will show you how it works, how to study, what to learn & more!

How To Learn Anything: Faster And More Efficiently preview
How To Learn Anything: Faster And More Efficiently

Want to learn a new skill? Here are 19 tips, techniques, and tactics that you can use to learn (and remember) absolutely anything, today!