50 Python Interview Questions (Junior to Senior)

Python is consistently one of the most in-demand programming languages, powering everything from web development and data science to artificial intelligence. Whether you are aiming for your first junior developer position or a staff engineering role, the Python interview will test both your knowledge of the syntax and your grasp of deeper architectural concepts.

We've compiled 50 essential Python interview questions, categorized by experience level, to help you prepare.

Python Interview Preparation


🟢 Junior Level: Foundations & Basics

At the junior level, interviewers want to ensure you know your way around Python's basic syntax, data types, and core mechanics.

  1. What are the key features of Python? Answer: Python is interpreted, dynamically typed, object-oriented, and has a massive standard library. It emphasizes readability and cleaner code.
  2. What is the difference between lists and tuples? Answer: Lists are mutable (can be changed) and use square brackets []. Tuples are immutable and use parentheses ().
  3. How does Python handle memory management? Answer: Python uses an automatic garbage collection system, primarily based on reference counting and a cyclic garbage collector.
  4. Explain the difference between == and is. Answer: == checks for value equality, while is checks for object identity (whether they point to the exact same memory location).
  5. What is a lambda function? Answer: An anonymous, inline function defined using the lambda keyword, typically used for short, simple operations.
  6. What are decorators? (Basic understanding) Answer: A decorator is a function that takes another function and extends its behavior without explicitly modifying it.
  7. How do you handle exceptions in Python? Answer: Using try, except, else, and finally blocks to catch errors gracefully and ensure cleanup code runs.
  8. What does the __init__ method do? Answer: It's the constructor method in object-oriented Python, called automatically when a new instance of a class is created.
  9. Explain list comprehensions with an example. Answer: A visually concise way to create lists. Example: [x*2 for x in range(10)].
  10. What is the purpose of self in Python classes? Answer: self represents the instance of the class and is used to access variables and methods associated with that specific object.
  11. How do you open and read a file safely? Answer: Using the with open('file.txt', 'r') as f: context manager, which ensures the file is closed automatically.
  12. What are the basic built-in data types in Python? Answer: Integers, floats, strings, booleans, lists, tuples, sets, and dictionaries.
  13. How do you copy an object in Python? Answer: Using copy.copy() for a shallow copy (copies references) and copy.deepcopy() for a deep copy (recursively copies all nested objects).
  14. What is PEP 8? Answer: The official style guide for writing Python code, focusing on readability and consistency (e.g., using 4 spaces for indentation).
  15. What does the pass statement do? Answer: It's a null operation used as a placeholder when a statement is syntactically required but you have no code to execute yet.

🔵 Mid-Level: Data Structures & Core Mechanics

Once you have a few years of experience, interviews shift towards how effectively you can use Python's built-in data structures and handle more complex scenarios.

Python Data Structures Diagram

  1. Explain the concept of Duck Typing in Python. Answer: "If it walks like a duck and quacks like a duck, it's a duck." Python focuses on an object's behavior (its methods and properties) rather than its explicit class type.
  2. How are dictionaries implemented internally? Answer: Dictionaries in Python are implemented as hash tables. They provide O(1) average time complexity for lookups, insertions, and deletions.
  3. What are generators and how are they different from normal functions? Answer: Generators use the yield keyword instead of return to produce a sequence of values lazily over time, saving memory compared to returning a full list.
  4. What is the Global Interpreter Lock (GIL)? Answer: A mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes at once in standard CPython.
  5. Explain how *args and **kwargs work. Answer: They allow functions to accept an arbitrary number of positional arguments (as a tuple) and keyword arguments (as a dictionary), respectively.
  6. What is monkey patching? Answer: Dynamically modifying a class or module at runtime, often used for hot-fixing bugs or testing (mocking).
  7. Explain the difference between @staticmethod and @classmethod. Answer: @classmethod takes cls (the class) as its first argument and can access class state. @staticmethod takes no implicit first argument and acts like a regular function housed inside a class namespace.
  8. What are Magic Methods (Dunder Methods)? Answer: Methods surrounded by double underscores (e.g., __str__, __add__) that allow you to define custom behavior for built-in operations (like printing or adding objects).
  9. How do you merge two dictionaries in modern Python (3.9+)? Answer: Use the union operator | (e.g., dict1 | dict2) or the in-place update operator |=.
  10. What is the time complexity of searching an element in a Set vs a List? Answer: O(1) average for a Set (due to hash table implementation) versus O(N) for a List.
  11. What does the __slots__ attribute do? Answer: It tells Python to use a static, memory-efficient structure for class instances instead of a dynamic dictionary, reducing memory overhead significantly.
  12. Explain context managers and how to build your own. Answer: Objects that handle setup and teardown logic using the with statement. You build them by defining __enter__ and __exit__ methods or using the @contextlib.contextmanager decorator.
  13. How does sorting work in Python? Answer: Python uses Timsort, a hybrid sorting algorithm derived from merge sort and insertion sort, optimized for real-world data with existing ordered runs.
  14. What is the difference between a module and a package? Answer: A module is a single .py file. A package is a directory containing multiple modules and an __init__.py file (though __init__.py is optional in newer Python versions).
  15. How do you manage dependencies and virtual environments? Answer: Using tools like venv, virtualenv, or Pipenv to isolate project packages, and relying on a requirements.txt or pyproject.toml file.
  16. Explain the zip() function and its common use cases. Answer: It takes iterables and aggregates them in a tuple-by-tuple fashion. Commonly used for parallel iteration or creating dictionaries from two lists.
  17. What is method resolution order (MRO) and super()? Answer: MRO determines the order in which Python searches for base classes during multiple inheritance (using the C3 linearization algorithm). super() delegates method calls to parent or sibling classes.
  18. Can you explain closures in Python? Answer: A function object that remembers values in its enclosing scope even if they are not present in memory. Used extensively in decorators.
  19. What is negative indexing and when would you use it? Answer: Using negative numbers to access elements from the end of a sequence (e.g., list[-1] accesses the last element).
  20. Why are default arguments evaluated only once? Answer: Default argument values are evaluated when the function definition is executed, meaning mutable defaults (like [] or {}) are shared across all calls unless handled carefully (e.g., setting the default to None).

🟣 Senior Level: Advanced Concepts & Architecture

Senior interviews focus on system architecture, concurrency, optimization, and advanced metaprogramming features.

Advanced Python Concepts

  1. How would you bypass the GIL for CPU-bound tasks? Answer: Use the multiprocessing module instead of threading. Each process gets its own Python interpreter and memory space, bypassing the GIL entirely.
  2. Explain the mechanics of asyncio and the event loop. Answer: asyncio uses an event loop to cooperatively schedule and run asynchronous tasks. It's ideal for I/O bound operations (like fetching web pages or querying databases) within a single thread.
  3. What are metaclasses and when would you use them? Answer: Metaclasses are the "classes of classes." They define how a class behaves. You use them when you need to intercept class creation, modify class dictionaries, or enforce patterns (like Singletons or ORMs).
  4. How would you optimize a Python application that uses too much memory? Answer: Common strategies include using generators instead of lists, employing __slots__ in classes to remove the __dict__ overhead, or utilizing libraries like NumPy for large datasets.
  5. Explain the descriptor protocol in Python. Answer: Descriptors are objects with __get__, __set__, or __delete__ methods. They are the mechanism behind properties, methods, static methods, and super.
  6. Compare Threading vs Multiprocessing vs Asyncio. When to use which? Answer: Use threading for blocking I/O (like file reads), asyncio for scalable non-blocking I/O (like network requests), and multiprocessing for CPU-heavy tasks.
  7. How does Python's execution model (bytecodes and PVM) work? Answer: Python source code is compiled down to lower-level, platform-independent bytecode (.pyc files), which is then interpreted by the Python Virtual Machine (PVM) line by line.
  8. What is the difference between __new__ and __init__? Answer: __new__ is responsible for creating and returning a new instance (called first), while __init__ initializes the existing instance.
  9. How would you handle memory leaks in a long-running Python process? Answer: Identify cyclically referenced objects, utilize weak references where appropriate, profile with tools like tracemalloc, and ensure large data structures are properly cleared.
  10. What are weak references (weakref) and why are they useful? Answer: A reference to an object that does not increase its reference count. This allows the object to be garbage collected, preventing memory leaks in caching or observer patterns.
  11. How can you write C extensions for Python? Answer: You can use the standard C-API, Cython, or ctypes/cffi to write or interface with C/C++ code, typically to drastically improve CPU execution speed.
  12. What is the difference between bounded and unbounded methods? Answer: A bounded method is bound to an instance (passing self automatically), whereas an unbounded method is just a function sitting in a class namespace that needs an instance explicitly passed if called.
  13. How do abstract base classes (ABCs) work in Python? Answer: Using the abc module, they provide a blueprint by defining abstract methods that must be strictly implemented by any concrete subclass, enforcing structural consistency.
  14. Explain how Python imports and caches modules internally (sys.modules). Answer: Python checks the sys.modules dictionary first. If a module is found, it uses the cached version. If not, it loads, compiles, and executes the module, then caches it for future imports.
  15. How would you design a scalable microservice architecture in Python? Answer: Use asynchronous frameworks (e.g., FastAPI), decouple services via message brokers (RabbitMQ or Kafka), implement robust containerization (Docker/Kubernetes), and establish strong API contracts.

Final Thoughts

The goal of your preparation shouldn't just be memorizing these answers, but understanding the core why behind them. When answering these in an interview, try to tie the concept back to a real-world problem you've solved in past projects.

Good luck with your Python interview! 🐍