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?
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.
99.9% of technical coding interviews are run by a member of the programming team, and feature:
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.
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.
2 things:
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.
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…
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.
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.
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.
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.
PEP-8 is the official style guidelines and recommendations for writing code in Python. Everything from naming convention advice and layout tips.
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
The easiest way to debug Python code is to install a debugger module such as pdb (python debugger).
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.
Modules are Python files (.py) that contain Python code and functions, which can be imported into another Python program.
For example
Python packages are simply namespaces that contain multiple modules.
A module is a single Python file that you can import and reuse, while a package is a collection of modules.
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:
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).
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
Literals are simply notations for a fixed value in code. These can be:
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:
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
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.
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.
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.
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.
There are 3 core things to understand when we talk about Python and its memory management:
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.
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}]
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.
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.