Python Top 50 Interview Questions and Answers

1. What are Python’s key features?

  • Easy to learn and use with a simple syntax.
  • Interpreted language with line-by-line execution.
  • Dynamically typed, meaning no explicit declaration of variable types.
  • Object-oriented, supporting classes and objects.
  • Extensive libraries for various tasks.
  • Portability across different platforms.

2.  What is the difference between lists and tuples in Python?

  • Lists are mutable (elements can be changed) and are defined using square brackets [].
  • Tuples are immutable (elements cannot be changed) and are defined using parentheses ().

3. What is a Python decorator?

  • A decorator is a function that extends the behavior of another function without modifying its structure.
  • It is used for adding functionalities like logging, authentication, and validation.

4. How does Python handle memory management?

  • Python uses reference counting and garbage collection.
  • When an object’s reference count drops to zero, the memory is reclaimed.
  • Garbage collection handles cyclic references.

5. What are list comprehensions and generator expressions?

  • List comprehensions provide a concise way to create lists using a syntax.
  • Generator expressions use parentheses and generate items lazily, which is memory efficient.

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

  • The GIL is a mutex that allows only one thread to execute Python bytecode at a time, simplifying memory management but potentially limiting performance in CPU-bound multi-threaded programs.

7. What are Python’s built-in data types?

  • Numeric types: int, float, complex
  • Sequence types: list, tuple, range
  • Text type: str
  • Mapping type: dict
  • Set types: set, frozenset
  • Boolean type: bool
  • Binary types: bytes, bytearray, memoryview

8. How can you handle exceptions in Python?

  • Exceptions are handled using try, except, else, and finally blocks to manage and respond to errors in a controlled manner.

9. What is a lambda function in Python?

  • A lambda function is a small anonymous function defined using the lambda keyword.
  • It can have any number of arguments but only one expression, making it useful for short, throwaway functions.

10. What is the difference between __init__ and __new__ methods in Python?

  • __init__ is the initializer method called after an object is created, used to initialize the object’s attributes.
  • __new__ is the constructor method called to create a new instance of a class, returning the new object and being called before __init__.

Related articles