Skip to content

100 Python interview questions with their answers:

Python Basics

  1. What is Python?

    • Python is an interpreted, high-level, general-purpose programming language that emphasizes readability, simplicity, and flexibility.
  2. What are Python's key features?

    • Key features include dynamic typing, garbage collection, readability, support for both procedural and object-oriented programming, and extensive standard libraries.
  3. What are Python's data types?

    • Python supports several built-in data types: int, float, str, list, tuple, dict, set, bool, NoneType.
  4. What is the difference between list and tuple?

    • Lists are mutable (can be changed), whereas tuples are immutable (cannot be changed after creation).
  5. What is a dictionary in Python?

    • A dictionary is a collection of key-value pairs where keys are unique and values can be of any type.
  6. What is a set in Python?

    • A set is an unordered collection of unique elements, supporting operations like union, intersection, and difference.
  7. What is the difference between del and remove in Python?

    • del deletes the object or item by index, while remove deletes an item by value.
  8. What are Python functions?

    • Functions in Python are defined using the def keyword, and they allow you to encapsulate logic for reuse.
  9. How can you declare a variable in Python?

    • Variables are declared by assigning a value to a name: x = 10.
  10. What is the None object in Python?

    • None is a special constant that represents the absence of a value or a null value.

Control Flow and Loops

  1. What is the difference between break, continue, and pass?

    • break: Exits the current loop.
    • continue: Skips the current iteration and moves to the next one.
    • pass: A placeholder, does nothing.
  2. What are if, elif, and else in Python?

    • if: Executes a block of code if a condition is true.
    • elif: Executes a block of code if the previous condition(s) are false, and a new condition is true.
    • else: Executes a block of code if no preceding conditions are true.
  3. How do you loop through a list in Python?

    • Use a for loop: for item in my_list:
  4. What is the range() function?

    • range() generates a sequence of numbers, commonly used in loops: range(start, stop, step).
  5. How does the while loop work?

    • A while loop repeatedly executes a block of code as long as a given condition is true.

Functions and Lambda Expressions

  1. What is a function in Python?

    • A function is a block of reusable code that performs a specific task, defined using the def keyword.
  2. What is a lambda function in Python?

    • A lambda function is a small anonymous function defined with the lambda keyword. Example: lambda x: x + 2.
  3. What is a return statement in Python?

    • A return statement is used to exit a function and optionally return a value.
  4. What are default arguments in Python functions?

    • Default arguments are parameters that have a predefined value. Example: def func(a, b=5):
  5. What is variable-length argument list in Python?

    • You can pass a variable number of arguments to a function using *args (for non-keyword arguments) and **kwargs (for keyword arguments).

Object-Oriented Programming (OOP)

  1. What is OOP?

    • Object-Oriented Programming is a paradigm based on objects and classes. It focuses on encapsulating data and functionality together.
  2. What is a class in Python?

    • A class is a blueprint for creating objects, defining properties and behaviors.
  3. What is an object in Python?

    • An object is an instance of a class containing both data (attributes) and methods (functions).
  4. What are the four principles of OOP?

    • Encapsulation, Abstraction, Inheritance, and Polymorphism.
  5. What is inheritance in Python?

    • Inheritance allows a class to inherit attributes and methods from another class, enabling code reuse.
  6. What is polymorphism in Python?

    • Polymorphism allows different classes to provide a method with the same name but different behaviors.
  7. What is encapsulation in Python?

    • Encapsulation is the bundling of data and methods that operate on the data within a class. It hides the internal state and allows access through methods.
  8. What is abstraction in Python?

    • Abstraction allows the hiding of complex implementation details while exposing only the necessary parts of the object.
  9. What is the self keyword in Python?

    • self refers to the instance of the class, allowing access to instance attributes and methods.
  10. What is the purpose of __init__ in Python?

    • __init__ is a special method used to initialize the object's attributes when an instance is created.

Modules and Packages

  1. What is a module in Python?

    • A module is a file containing Python definitions and statements that can be imported into other programs.
  2. What is a package in Python?

    • A package is a collection of Python modules organized in directories.
  3. How do you import a module in Python?

    • You can import a module using the import keyword: import module_name.
  4. What is the difference between import and from import?

    • import imports the whole module, while from ... import allows importing specific functions or variables.
  5. What is the purpose of the __name__ variable?

    • The __name__ variable indicates the name of the module or script. It is __main__ when the script is executed directly.

Exception Handling

  1. What is exception handling in Python?

    • Exception handling is a mechanism to handle runtime errors using try, except, else, and finally.
  2. What is the purpose of try, except, else, and finally?

    • try: Block of code to attempt to execute.
    • except: Block of code to handle exceptions.
    • else: Block of code to run if no exceptions are raised.
    • finally: Block of code that runs regardless of whether an exception was raised.
  3. What is the difference between Exception and Error?

    • Exception is a base class for all exceptions, while Error refers to serious issues that are generally not caught by normal exception handling (e.g., MemoryError).
  4. What is a custom exception?

    • A custom exception is a user-defined class that extends the Exception class.
  5. What is the raise keyword in Python?

    • The raise keyword is used to throw an exception explicitly in your code.

Advanced Python Concepts

  1. What is a generator in Python?

    • A generator is a function that returns an iterator, yielding values one at a time using the yield keyword.
  2. What are decorators in Python?

    • Decorators are functions that modify the behavior of other functions or methods.
  3. What is the difference between deepcopy() and copy() in Python?

    • copy() creates a shallow copy, while deepcopy() creates a new object and recursively copies all nested objects.
  4. What are metaclasses in Python?

    • Metaclasses define how classes are created. They allow customization of class creation and behavior.
  5. What is a context manager in Python?

    • A context manager is used to manage resources, such as opening and closing files, using the with statement.
  6. What is the purpose of global keyword in Python?

    • The global keyword allows access to a global variable inside a function.
  7. What is the purpose of nonlocal keyword in Python?

    • The nonlocal keyword is used to modify variables in the nearest enclosing scope that is not global.
  8. What is a staticmethod in Python?

    • A staticmethod is a method that does not depend on instance variables or methods and can be called directly on the class.
  9. What is a classmethod in Python?

    • A classmethod is a method that takes the class as the first argument, and it is bound to the class rather than an instance.
  10. What is the with statement in Python?

    • The with statement simplifies resource management by ensuring that resources are properly acquired and released (e.g., for file handling).

Libraries and Frameworks

  1. What is NumPy?

    • NumPy is a Python library used for numerical computations, particularly for handling arrays and matrices.
  2. What is Pandas?

    • Pandas is a Python library used for data manipulation and analysis, providing data structures like DataFrames.
  3. What is Matplotlib?

    • Matplotlib is a plotting library for Python, used to create static, animated, and interactive visualizations.
  4. What is Flask?

    • Flask is a micro web framework for Python that is used to build web applications.
  5. What is Django?

    • Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
  6. What is requests in Python?

    • requests is a popular library for making HTTP requests, handling things like headers, cookies, and response data.
  7. What is SQLAlchemy?

    • SQLAlchemy is an Object Relational Mapping (ORM) library for Python, used to interact with databases using Python objects.
  8. What is TensorFlow?

    • TensorFlow is an open-source machine learning framework developed by Google for building and training neural networks.
  9. What is Keras?

    • Keras is a high-level neural networks API written in Python, running on top of frameworks like TensorFlow.
  10. What is scikit-learn?

    • scikit-learn is a machine learning library for Python that provides simple and efficient tools for data analysis and modeling.

Python Best Practices

  1. What are Python's PEP 8 guidelines?

    • PEP 8 is the style guide for Python code, recommending practices like using 4 spaces for indentation, proper naming conventions, and line length restrictions.
  2. What is the significance of __str__ and __repr__?

    • __str__ is used for creating a user-friendly string representation of an object, while __repr__ is meant for a more formal representation that can be used to recreate the object.
  3. What is list comprehension in Python?

    • List comprehension provides a concise way to create lists based on existing lists or iterables. Example: [x for x in range(10)].
  4. What is the purpose of assert in Python?

    • The assert statement is used for debugging purposes, ensuring that a condition holds true during program execution.
  5. What is the zip() function in Python?

    • zip() combines multiple iterables element-wise into tuples. Example: zip([1, 2], ['a', 'b']) returns [(1, 'a'), (2, 'b')].
  6. What is the difference between del and remove() in a list?

    • del removes an item by index, while remove() removes an item by value.
  7. How do you handle missing data in a pandas DataFrame?

    • You can handle missing data using dropna() or fillna() methods in pandas.
  8. What is the difference between filter() and map() in Python?

    • filter() filters items based on a condition, while map() applies a function to each item in an iterable.
  9. What is the difference between join() and split() in Python?

    • join() concatenates a list of strings into one string, while split() breaks a string into a list based on a delimiter.
  10. What is the use of itertools in Python?

    • itertools is a module providing functions for creating iterators that operate on items of an iterable, such as permutations and combinations.

Multithreading and Multiprocessing

  1. What is the difference between threading and multiprocessing?

    • threading allows for concurrent execution of code using threads, while multiprocessing runs code in separate processes.
  2. What is the Global Interpreter Lock (GIL)?

    • The GIL is a mechanism that ensures only one thread executes Python bytecode at a time, limiting the concurrency of multi-threaded programs.
  3. How can you create a thread in Python?

    • You can create a thread by using the threading.Thread() class and passing the target function to it.
  4. What is a lock in Python threading?

    • A lock is a synchronization primitive used to ensure that only one thread accesses a shared resource at a time.
  5. What is the queue module in Python?

    • The queue module provides a thread-safe FIFO implementation for passing data between threads or processes.

File I/O and Serialization

  1. How do you read a file in Python?

    • Use the open() function and read() method: with open('file.txt', 'r') as f: content = f.read().
  2. What is the difference between open('file', 'r') and open('file', 'w')?

    • 'r' opens the file in read mode, while 'w' opens the file in write mode (creating a new file if it doesn't exist).
  3. How do you write to a file in Python?

    • Use the write() or writelines() method: with open('file.txt', 'w') as f: f.write('Hello World!').
  4. What is serialization in Python?

    • Serialization is the process of converting an object into a byte stream, commonly using pickle or json modules.
  5. What is pickle in Python?

    • pickle is a Python module used for serializing and deserializing objects into byte streams.

Python Debugging and Testing

  1. What is a debugger in Python?

    • A debugger allows you to step through your code to inspect and troubleshoot it. Python provides the built-in pdb debugger.
  2. What is unittest in Python?

    • unittest is Python’s built-in framework for writing and running tests, supporting test discovery and execution.
  3. What is the purpose of assertEqual() in unittest?

    • assertEqual() checks whether two values are equal in unit tests.
  4. What is mock in Python testing?

    • mock is a library used for creating mock objects to simulate and control parts of the code in tests.
  5. What is the difference between assertTrue and assertFalse in unittest?

    • assertTrue checks if a condition is True, while assertFalse checks if a condition is False.

Performance Optimization

  1. What are Python's performance bottlenecks?

    • Performance bottlenecks can include inefficient use of data structures, redundant computations, excessive memory usage, and inefficient algorithms.
  2. What is cProfile in Python?

    • cProfile is a built-in module used for profiling Python programs to identify performance issues.
  3. What are some ways to improve performance in Python?

    • Using built-in functions and libraries, optimizing algorithms, using list comprehensions, and using NumPy for numerical computations.
  4. What is the difference between range() and xrange() in Python 2?

    • In Python 2, range() returns a list, while xrange() returns an iterator. In Python 3, range() behaves like xrange().
  5. What is the use of timeit module in Python?

    • The timeit module is used for measuring execution time of small code snippets.

Python Deployment

  1. How can you create an executable from a Python script?

    • You can create an executable using tools like PyInstaller or cx_Freeze.
  2. What is a virtual environment in Python?

    • A virtual environment is an isolated environment where you can install and manage dependencies independently from the system installation.
  3. How do you deploy a Python application?

    • Deployment involves packaging the application, managing dependencies, setting up the environment, and running the application on the target platform.
  4. What is pip in Python?

    • pip is Python’s package manager, used for installing and managing Python libraries.
  5. What is Docker and how is it used with Python?

    • Docker is a tool for creating containerized applications. It can be used to package and deploy Python applications consistently across environments.

Concurrency and Parallelism

  1. What is the difference between concurrency and parallelism?

    • Concurrency allows multiple tasks to run in an overlapping manner, while parallelism executes tasks simultaneously.
  2. How do you create concurrent programs in Python?

    • Use the threading, multiprocessing, or asyncio modules for creating concurrent programs.
  3. What is asyncio in Python?

    • asyncio is a module for writing asynchronous programs using coroutines, events, and non-blocking I/O.
  4. What is the async keyword in Python?

    • The async keyword defines a coroutine function that can be used with await.
  5. How do you manage shared state between threads in Python? - You can use synchronization primitives such as Lock, Semaphore, or Queue from the threading module.


This concludes the 100 Python interview questions.

J2J Institute private limited