If you’re preparing for a Python job interview, you’ll likely be asked a variety of questions about your experience and skills. In this blog post, we’ll go over 20 common Python interview questions and answers to help you prepare for your upcoming interview.
By reviewing these questions and answers, you’ll gain a better understanding of what to expect in your Python job interview and feel more confident in your ability to answer any questions that come your way. Let’s get started!
What is Python and what is it used for?
Python is a high-level, interpreted programming language that is used for a wide range of applications, including web development, scientific computing, data analysis, and artificial intelligence.
# example of a Python script
print("Hello, world!")
What is the difference between a list and a tuple in Python?
A list is a collection of ordered, mutable elements that can contain duplicate values. A tuple is a collection of ordered, immutable elements that can also contain duplicate values. The main difference between a list and a tuple is that a list is mutable, which means it can be modified after it is created, while a tuple is immutable, which means it cannot be modified once it is created.
# example of a list
lst = ["hello", "world"]
# add an element to the list
lst.append("!")
# example of a tuple
tup = ("hello", "world")
# try to modify the tuple
tup[0] = "!" # this will raise an error
What is a dictionary in Python and how is it used?
A dictionary is a collection of key-value pairs that is used to store and retrieve data efficiently. A dictionary is implemented as a hash table, where the keys are hashed according to their hash code and are stored in the hash table using the calculated hash value as the index. A dictionary provides constant-time performance for the basic operations, such as insert, delete, and lookup.
# example of a dictionary
d = {
"hello": "world",
"foo": "bar"
}
# add a new key-value pair to the dictionary
d["baz"] = "qux"
# retrieve a value from the dictionary
print(d["hello"]) # "world"
Can you explain the difference between a list and a set in Python?
A list is a collection of ordered, mutable elements that can contain duplicate values. A set is a collection of unordered, mutable elements that does not allow duplicate values. The main difference between a list and a set is that a list preserves the order of its elements, while a set does not. A set also does not allow duplicate elements, while a list allows duplicate elements.
# example of a list
lst = [1, 2, 3, 3]
# example of a set
s = {1, 2, 3}
# try to add a duplicate element to the set
s.add(3) # this will not add the element, because it is a duplicate
# convert the set to a list
lst = list(s)
What is the difference between a static method and a class method in Python?
A static method is a method that belongs to a class, rather than to an instance of a class. A static method is called directly on the class, without the need to create an object. A static method is typically used to implement utility functions that are not tied to a specific object. A class method is a method that belongs to a class and is called on the class, but it receives the class as the first argument, which is usually called cls
. A class method is used to define methods that operate on the class itself, rather than on instances of the class.
class Example:
# static method
@staticmethod
def static_method():
pass
# class method
@classmethod
def class_method(cls):
pass
# call the static method
Example.static_method()
# call the class method
Example.class_method()
What is a generator function and how is it used in Python?
A generator function is a function that returns an iterator, which is an object that implements the iterator protocol. A generator function allows the programmer to define a function that can return multiple values, one at a time, using the yield
keyword. A generator function is used to create iterators that can be used in loops or with other functions that consume iterators, such as map
, filter
, and reduce
.
# example of a generator function
def generator_function(x):
yield x ** 2
yield x ** 3
# create an iterator from the generator function
it = generator_function(2)
# iterate over the values in the iterator
for x in it:
print(x)
The Output of the above code would be
4
8
Can you explain the difference between inheritance and composition in Python?
Inheritance is a mechanism that allows a class to inherit attributes and methods from a parent class. Inheritance is used to create a hierarchy of classes, where a derived class can inherit attributes and methods from a base class. Composition is a mechanism that allows a class to contain objects of other classes as attributes. Composition is used to create complex objects by combining simpler objects, where a composed class can contain objects of other classes as attributes.
# example of inheritance
class Base:
def foo(self):
print("Inside the base class")
class Derived(Base):
pass
# create an object of the derived class
obj = Derived()
# call the method inherited from the base class
obj.foo()
# example of composition
class Base:
def foo(self):
print("Inside the base class")
class Composed:
def __init__(self):
self.base = Base()
# create an object of the composed class
obj = Composed()
# call the method on the contained object
obj.base.foo()
What is the difference between a regular function and a lambda function in Python?
A regular function is a function that is defined using the def
keyword and has a name. A regular function can have any number of arguments and a return statement. A lambda function is a function that is defined using the lambda
keyword and has no name. A lambda function can have any number of arguments, but only one expression, which is evaluated and returned. A lambda function is used to define short, anonymous functions that can be passed as arguments to other functions or used as a part of a larger expression.
# example of a regular function
def func(x, y):
return x + y
# call the regular function
print(func(1, 2))
The Output of the above code would be
3
# example of a lambda function
func = lambda x, y: x + y
# call the lambda function
print(func(1, 2))
The Output of the above code would be
3
Can you explain how exception handling works in Python?
Exception handling is a mechanism that allows a program to handle runtime errors and continue executing. In Python, exception handling is done using the try
and except
keywords. The try
keyword defines a block of code that is executed, and the except
keyword defines a block of code that is executed if an exception is raised in the try
block. The except
keyword can be used with a specific exception type or with the Exception
class to catch any type of exception.
# example of exception handling
try:
# try to execute a risky statement
x = 1 / 0
# catch the ZeroDivisionError exception
except ZeroDivisionError:
# print an error message
print("Division by zero is not allowed")
The Output of the above code would be
Division by zero is not allowed
# example of catching any exception
try:
# try to execute a risky statement
x = 1 / 0
# catch any exception
except Exception as e:
# print the type and value of the exception
print(type(e), e)
The Output of the above code would be
<class 'ZeroDivisionError'> division by zero
Can you explain the difference between a mutable and an immutable object in Python?
A mutable object is an object that can be modified after it is created. A mutable object can have its attributes or elements changed. An immutable object is an object that cannot be modified after it is created. An immutable object cannot have its attributes or elements changed.
# example of a mutable object
# create a list
lst = [1, 2, 3]
# change the elements of the list
lst[0] = 4
lst[1] = 5
lst[2] = 6
# print the modified list
print(lst)
The Output of the above code would be
[4, 5, 6]
# example of an immutable object
# create a tuple
tpl = (1, 2, 3)
# try to change the elements of the tuple
try:
tpl[0] = 4
tpl[1] = 5
tpl[2] = 6
# catch the TypeError exception
except TypeError:
# print an error message
print("Cannot modify an immutable object")
# print the unchanged tuple
print(tpl)
The Output of the above code would be
Cannot modify an immutable object
(1, 2, 3)
What is the difference between a stack and a queue in Python?
A stack is a data structure that follows the Last In First Out (LIFO) principle. A stack is used to store and retrieve elements in a sequential order, where the last element added to the stack is the first element retrieved from the stack. A queue is a data structure that follows the First In First Out (FIFO) principle. A queue is used to store and retrieve elements in a sequential order, where the first element added to the queue is the first element retrieved from the queue.
# example of a stack
# create an empty stack
stack = []
# push elements onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
# pop elements from the stack
print(stack.pop())
print(stack.pop())
print(stack.pop())
The Output of the above code
3
2
1
# example of a queue
# create an empty queue
queue = []
# enqueue elements onto the queue
queue.append(1)
queue.append(2)
queue.append(3)
# dequeue elements from the queue
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
The Output of the above code would be
1
2
3
Can you explain the difference between a list comprehension and a generator expression in Python?
A list comprehension is a concise way to create a list from a sequence of values by applying a transform function and a filter condition to each value in the sequence. A list comprehension consists of square brackets containing an expression that defines the elements of the list, followed by a for
clause that defines the sequence of values to iterate over, and an optional if
clause that defines the filter condition. The elements of the list are the results of applying the transform function to each value in the sequence that satisfies the filter condition.
# example of a list comprehension
# create a list of squares of the numbers from 1 to 10
my_list = [x**2 for x in range(1, 11)]
# print the list
print(my_list)
The output of the code above will be:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
What is a decorator in Python and how is it used?
A decorator is a function that takes another function as an argument and extends the behavior of the original function without modifying its code. A decorator is used to add additional functionality to an existing function, without changing the structure of the original function. Decorators are often used to implement common patterns, such as caching, logging, and authentication.
# example of a decorator function
def decorator(func):
# define the wrapper function
def wrapper():
# add additional functionality
print("Before the decorated function is called")
# call the decorated function
func()
# add additional functionality
print("After the decorated function is called")
# return the wrapper function
return wrapper
# example of a decorated function
@decorator
def foo():
print("Inside the decorated function")
# call the decorated function
foo()
// THE OUTPUT OF THE CODE ABOVE
Before the decorated function is called
Inside the decorated function
After the decorated function is called
Can you explain the difference between the map
and filter
functions in Python?
The map
function is a built-in function that applies a given function to each element of an iterable and returns a new iterable with the results. The filter
function is a built-in function that filters an iterable based on a given condition and returns a new iterable with the elements that satisfy the condition.
# example of the map function
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
# create a function to square a number
def square(x):
return x ** 2
# apply the square function to each element of the list of numbers
squares = map(square, numbers)
# print the list of squares
print(list(squares))
The Output of the above code would be
[1, 4, 9, 16, 25]
# example of the filter function
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
# create a function to check if a number is odd
def is_odd(x):
return x % 2 == 1
# filter the list of numbers to get the odd numbers
odd_numbers = filter(is_odd, numbers)
# print the list of odd numbers
print(list(odd_numbers))
The Output of the above code would be
[1, 3, 5]
What is the difference between a local and a global variable in Python?
A local variable is a variable that is defined inside a function and is only visible and accessible inside the function. A local variable can be accessed only within the body of the function in which it is defined, and it cannot be accessed outside the function. A global variable is a variable that is defined outside any function and is visible and accessible in all functions in the program. A global variable can be accessed and modified by any function in the program.
# example of a local variable
# define a function that has a local variable
def func():
# define a local variable
local_var = 1
# print the local variable
print(local_var)
# try to access the local variable from outside the function
try:
print(local_var)
# catch the NameError exception
except NameError:
# print an error message
print("Variable is not defined")
The output of the code above will be:
Variable is not defined
# example of a global variable
# define a global variable
global_var = 1
# define a function that uses the global variable
def func():
# print the global variable
print(global_var)
# call the function to print the global variable
func()
The output of the code above will be:
1
Can you explain the difference between a module and a package in Python?
A module is a Python file that contains definitions and statements that can be imported and used in another Python file. A package is a directory that contains one or more Python modules, and a __init__.py
file that specifies which modules should be imported when the package is imported. A package can be imported and used in the same way as a module, but it allows for a hierarchical organization of modules, and it allows for modules with the same name to be used in different parts of the package hierarchy.
# example of a module
# create a file called my_module.py
# define a function in the module
def my_function():
print("Hello from my_function() in my_module.py")
# example of a package
# create a directory called my_package
# create a file called __init__.py in the directory
# define a function in the __init__.py file
def my_function():
print("Hello from my_function() in __init__.py")
# create a file called my_module.py in the directory
# define a function in the my_module.py file
def my_function():
print("Hello from my_function() in my_module.py")
To import and use the functions defined in the module and the package, you can use the import
statement:
# import and use the function defined in the module
from my_module import my_function
my_function()
# import and use the function defined in the package
from my_package import my_function
my_function()
# import and use the function defined in the module inside the package
from my_package.my_module import my_function
my_function()
The output of the code above will be:
Hello from my_function() in my_module.py
Hello from my_function() in __init__.py
Hello from my_function() in my_module.py
What is the difference between a deep and a shallow copy in Python?
A shallow copy is a copy of an object that creates a new object with the same top-level elements as the original object, but it does not create new copies of the inner elements of the original object. A shallow copy shares the inner elements of the original object with the new object, so any changes made to the inner elements of the new object will also affect the original object. A deep copy is a copy of an object that creates a new object with new copies of the inner elements of the original object, so any changes made to the inner elements of the new object will not affect the original object.
# example of a shallow copy
# create a list
my_list = [1, 2, [3, 4]]
# create a shallow copy of the list
my_list_copy = my_list.copy()
# modify the inner list of the original list
my_list[2][0] = 5
# print the original and the copied lists
print(my_list)
print(my_list_copy)
The output of the code above will be:
[1, 2, [5, 4]]
[1, 2, [5, 4]]
# example of a deep copy
# import the deepcopy function from the copy module
from copy import deepcopy
# create a list
my_list = [1, 2, [3, 4]]
# create a deep copy of the list
my_list_copy = deepcopy(my_list)
# modify the inner list of the original list
my_list[2][0] = 5
# print the original and the copied lists
print(my_list)
print(my_list_copy)
The output of the code above will be:
[1, 2, [5, 4]]
[1, 2, [3, 4]]
Can you explain the difference between a recursive and an iterative function in Python?
A recursive function is a function that calls itself to solve a problem by dividing the problem into smaller subproblems. A recursive function must have a base case, which is a condition that terminates the recursion and returns a result, and it must have a recursive case, which is a condition that calls the function itself to solve the smaller subproblems. An iterative function is a function that uses a loop to solve a problem by repeating a set of operations until a condition is met. An iterative function does not call itself, and it does not need a base case or a recursive case.
# example of a recursive function
# define a function to calculate the factorial of a number
def factorial(n):
# if the number is zero, return one
if n == 0:
return 1
# if the number is not zero, return the product of the number and the factorial of the number minus one
else:
return n * factorial(n - 1)
# calculate the factorial of 5 using the recursive function
print(factorial(5))
The output of the code above will be:
120
# example of an iterative function
# define a function to calculate the factorial of a number
def factorial(n):
# initialize the result to one
result = 1
# iterate over the numbers from 1 to the number
for i in range(1, n + 1):
# multiply the result by the current number
result *= i
# return the result
return result
# calculate the factorial of 5 using the iterative function
print(factorial(5))
The output of the code above will be:
120
What is the difference between a list and a set in Python?
A list is an ordered sequence of elements that can contain duplicates, and it is defined using square brackets. A set is an unordered collection of unique elements, and it is defined using curly braces. A list allows for indexing and slicing, and it supports methods for adding, removing, and modifying elements. A set does not support indexing or slicing, and it supports methods for adding, removing, and checking for the presence of elements.
# example of a list
# create a list
my_list = [1, 2, 3, 3, 4, 5, 5]
# print the list
print(my_list)
# print the first element of the list
print(my_list[0])
# print the first three elements of the list
print(my_list[:3])
# add an element to the list
my_list.append(6)
# remove an element from the list
my_list.remove(3)
# print the list after adding and removing elements
print(my_list)
The output of the code above will be:
[1, 2, 3, 3, 4, 5, 5]
1
[1, 2, 3]
[1, 2, 4, 5, 5, 6]
# example of a set
# create a set
my_set = {1, 2, 3, 3, 4, 5, 5}
# print the set
print(my_set)
# try to print the first element of the set
try:
print(my_set[0])
# catch the TypeError exception
except TypeError:
# print an error message
print("Set does not support indexing")
# try to print the first three elements of the set
try:
print(my_set[:3])
# catch the TypeError exception
except TypeError:
# print an error message
print("Set does not support slicing")
# add an element to the set
my_set.add(6)
# remove an element from the set
my_set.remove(3)
# print the set after adding and removing elements
print(my_set)
The output of the code above will be:
{1, 2, 3, 4, 5}
Set does not support indexing
Set does not support slicing
{1, 2, 4, 5, 6}