Master Python Interview Questions with Answers

Posted by Vivek Shukla on May 22, 2023 under Python

Prepare for Python interview questions using this extensive list of questions and answers. This list takes you from beginner to intermediate to advanced level of python concepts in question-answer format.

You might want to bookmark this page as new contents will added and updated with time.

Beginner

What is Python?

  • Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.

  • Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.

  • It was created by Guido van Rossum and first released in 1991.

What are some of the benefits of using Python?

  • Python has a vast number of third-party modules and libraries that make it easy to incorporate additional functionality into your projects.

  • Python’s simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.

  • Python supports modules and packages, which encourages program modularity and code reuse.

  • It has a large and active community that provides support, resources, and libraries.

  • Python has a vast number of third-party modules and libraries that make it easy to incorporate additional functionality into your projects.

  • Python is an interpreted language, which means that it does not need to be compiled before running, making it faster to write and test code.

What is the difference between str and repr in Python?

coming soon

What is PEP8?

  • PEP8 is a coding style guide for Python.

  • It provides guidelines on how to write Python code that is easy to read and maintain.

  • PEP 8 covers topics such as indentation, naming conventions, comments and documentation, code layout and structure, imports, error handling, and best practices.

  • PEP 8 is not a strict set of rules, but rather a set of guidelines that are intended to be flexible and adaptable to different projects and contexts.

  • PEP stands for Python Enhancement Proposal, which is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment.

What is a List?

  • In Python, List is a data structure which is used to hold multiple items at once.

  • It is mutable and ordered sequence of elements.

  • They are similar to an array in other programming languages.

  • Python Lists are mutable and can hold items of different types simultaneously.

  • Lists are defined using []

  • Example: data = ["a", 1, "b", 2]

  • Elements in a list can be accessed using indexing, for example data[0] would return first element in the list.

What is a Tuple?

  • Tuple is an immutable and ordered sequence of elements.

  • Tuples are immutable which means they cannot be modified once created.

  • Since tuples are immutable, this also makes them hashable.

  • Tuples are defined using ()

  • Example: a_tuple = (1, 2, "a", 4)

  • Just like lists, tuples can also be accessed using indexing, i.e. a_tuple[0]

What is the difference between a List and a Tuple?

List Tuple
Lists are mutable Tuples are immutable
Lists are not hashable since they are mutable. Tuples are hashable
Defined using [] Defined using ()
Lists take more memory due to the overhead of managing dynamic memory allocation Tuples take less memory compared to lists
It is slower for accessing elements due to dynamic memory allocation Tuples are faster in accessing elements
It is suitable for situations when elements are needed to be frequently added or removed Tuples are suitable for situations where data needs to be fixed and does not need to be modified

What are virtual environments in Python?

  • Virtual environments are isolated environments which contain their own Python version and packages.

  • They allow you to create a separate environment for each project or application you are working on, with its own set of dependencies, without affecting the global environment or other projects.

  • This can be especially useful when working on multiple projects that require different versions of the same package or library.

  • Python virtual environments can be created using the venv module, which is included with Python 3.3 and later versions.

  • Example: python3 -m venv env_name

What is the difference between a function and a method in Python?

Function Method
A block of usable code that performs a task A function that is associated with an object
Defined outside of a class Defined inside a class
Can be called anywhere in the program Can only be called on an instance of the class
Accepts arguments and returns a value Accepts arguments but also can access and modify the attributes of the instance on which it is called upon
It is defined with the def keyword followed by function name and parameters Defined with def keyword followed by method name and parameters
It doesn’t have self parameter Implicit first argument is the object on which the method is called, self by convention
Example: len("world") Example: "world".lower()

What is an exception in Python?

  • An exception is an error that happens during execution of a program.

  • When an exception occurs, the normal flow of the program is disrupted and interpreter raises an exception object (of Exception class).

  • If exception is not handled then program will terminate.

  • Python provides built-in exceptions for common error conditions, such as IndexError, ValueError, TypeError, etc.

  • You can also create your own exception by inheriting from base Exception class.

How to handle Exceptions in Python?

  • Python provides a mechanism to handle exception using try-except blocks.

  • A try block contains the code that may cause the exception.

  • And except block contains the code that handles the exception.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("this is not how maths work")
  • You can also use a finally block after the except block to specify code that should be executed regardless of whether an exception was raised or not. The finally block is optional, but it’s useful for releasing resources or cleaning up after the code in the try block.

  • We also can have else block. The else block contains the code that is executed if no exception is raised in the try block. It is optional and executes after the try block but before the finally block.

How do you handle file I/O in Python?

  • Python provides built-in function open() to handle file I/O.

  • The open() function takes two arguments: name of the file and the mode in which to open the file (e.g. read, write, append, etc.).

  • To read data from a file, you can use the read() method, which reads the entire contents of the file, or the readline() method, which reads one line at a time.

  • To write data to a file, you can use the write() method, which writes a string to the file, or the writelines() method, which writes a list of strings to the file.

  • After you are done working with the file, you should close the file using the close() method.

What is a static method?

  • Static method is a method which belongs to class rather than instance of the class.

  • It does not have access to the instance or it’s attributes.

  • It does not require self parameter that instance method usually have.

  • Static methods are defined using the @staticmethod decorator.

class FooClass:
    @staticmethod
    def my_static_method():
        print("calling static method")

# Calling the static method without creating an instance of the class
FooClass.my_static_method()

What is a class method?

  • A class method is method that is bound to the class and not to the instance of the class.

  • Class method knows about the class and it’s attributes, but it can’t access individual instance or their attributes.

class BarClass:
    class_attribute = "a class attribute."

    @classmethod
    def my_class_method(cls):
        print("Class attribute:", cls.class_attribute)

# Calling the class method on the class itself
BarClass.my_class_method()

What are difference between static method and class method?

Static Method Class Method
Static method do not depend on the state of the class or instance Class method operate on the class
It does not take any special parameter Takes a special parameter called cls which refers to the class itself
Can be called on the class or instance of the class It can be called on the class but not on instance of the class
Cannot access or modify the class or instance state It can access and modify class state but not the instance state

What is the difference between an instance method and a class method in Python?

coming soon

What is the Global Interpreter Lock (GIL) in Python?

  • The Global Interpreter Lock (GIL) is a mechanism used in Python to manage access to shared resources, such as the Python interpreter itself.

  • The GIL is a mutex that prevents multiple threads from executing Python bytecodes at once.

  • The GIL is necessary because Python interpreter is not thread-safe, meaning that it is not designed to handle multiple threads executing Python code simultaneously.

  • The GIL is a feature of the CPython implementation of Python, which is the most widely used implementation.

  • The GIL can prevent multi-core processors from fully utilizing all available cores.

  • The GIL can be released using the threading module’s Lock object, the multiprocessing module, or by using an extension module written in C that releases GIL.

What is Python package?

  • A package is a way of organizing related modules into a single namespace.

  • A package is a directory that contains one or more Python modules, as well as an optional __init__.py file that initializes the package.

  • Packages can be imported using import statement.

  • Packages can be installed and distributed using tools such as pip and setuptools.

What is Python module?

  • A module is a file containing Python code that can be imported and used in other Python code.

  • A module can define classes, functions and variables that can be used in other Python code.

  • A module can be imported using import statement.

  • Modules can be organized into package which is a directory that contains one or more modules.

What is the difference between a shallow copy and a deep copy in Python?

coming soon

Intermediate

What is a Python namespace?

coming soon

What is the difference between a class and an object in Python?

coming soon

How do you implement inheritance in Python?

coming soon

How do you implement a singleton pattern in Python?

coming soon

What is a decorator?

  • A decorator is higher-order function that takes a function as input and returns a modified function as output.

  • Decorators are used to modify or enhance the behaviour of a function without changing it’s source code.

  • Decorators can be used with syntax @decorator_name where decorator_name is the name of decorator function.

def my_decorator(func):
    def wrapper():
        print("Before function is called.")
        func()
        print("After function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

What is a lambda function in Python?

  • A lambda function is an anonymous function that can be defined in a single line of code.

  • A lambda function is defined using lambda keyword followed by the function parameters, a colon and then the function body.

  • Example: lambda i, j: i * j

  • Lambda functions can take any number of arguments, but they can have only one expression in the body.

  • Lambda functions are often used as a shortcut for simple functions that are only used once.

What is a generator in Python?

  • A generator is type of iterable, like a list or a tuple, but it generates values on the fly instead of storing them in memory.

  • Since it doesn’t store values in memory, it is very memory efficient.

  • Generators can be iterated just like a list or a tuple but indexing is not possible.

  • Generators can be created using generator function or generator expression.

  • A generator function is created using one or more yield statements.

  • Whereas a generator expression is similar to list comprehension but instead of list it returns a iterator.

# generator function
def gen_number(limit):
    n = 0
    while n <= limit:
        yield n
        n += 1

# generator expression
numbers = (i for i in range(5))

What is the difference between a list comprehension and a generator expression in Python?

coming soon

What is a Python iterator?

coming soon

What is the difference between iterator and generator in Python?

coming soon

Advanced

What is a context manager in Python?

  • In Python, a context manager is an object that defines the methods __enter__() and __exit__(), which allows you to define a block of code that should be executed before and after a specific operation.

  • A context manager is used in a with statement, which guarantees that the __enter__() method is called before the block of code is executed, and the __exit__() method is called after the block of code is executed.

  • __enter__() method returns an object that can be used within the with block, and the __exit__() method is used to clean up or release any resources that were used by the with block.

class CustomContextManager:
    def __enter__(self):
        print("Entering the context.")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the context.")

    def do_something(self):
        print("Doing something.")

# Use the context manager to manage a resource
with CustomContextManager() as cm:
    cm.do_something()

How do you implement multithreading in Python?

coming soon

How do you handle data serialization in Python?

coming soon

What is the difference between pickle and cPickle in Python?

coming soon

What is a Python coroutine?

coming soon

What is the difference between a coroutine and a thread in Python?

coming soon

How do you implement operator overloading in Python?

coming soon

How do you implement garbage collection in Python?

coming soon

How do you handle memory management in Python?

coming soon

What is a metaclass in Python?

  • A metaclass is used to define the behavior of a class, such as how it is instantiated or how its attributes are accessed.

  • A metaclass is defined by creating a new class that inherits from type.

  • When a new class is defined, Python looks for a metaclass definition in the class definition, and if one is found, it uses that metaclass to create a new class.

class MyMeta(type):
    def __new__(cls, name, bases, attrs):
        # Modify attributes of the class being created
        attrs['additional_attr'] = 42
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=MyMeta):
    pass

# Accessing the additional attribute added by the metaclass
print(MyClass.additional_attr)  # Output: 42

Hope you benefited from the curation of these questions and answers. For further study you can also explore official python docs.

Built with  Svelte Starter Kit