Site icon FahmidasClassroom

Top 50 Python interview questions with answers

Python

Here are 50 common Python interview questions with detailed answers to help you prepare for interviews:

Basic Questions

  1. What is Python?
  1. What are Python’s key features?
  1. How do you create a variable in Python?
  1. What are Python’s built-in data types?
  1. What is a list in Python?
  1. How do you create a tuple in Python?
  1. What is a dictionary in Python?
  1. What is the difference between a list and a tuple?
  1. How do you access elements in a list?
  1. How do you handle exceptions in Python?
    • Exceptions are handled using try and except blocks. For example:
      python try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero")

Intermediate Questions

  1. What is the purpose of the self keyword in Python?
    • self refers to the instance of the class and is used to access instance attributes and methods within class methods.
  2. Explain list comprehension.
    • List comprehension provides a concise way to create lists. It consists of an expression followed by a for loop and optionally an if condition. Example:
    squares = [x**2 for x in range(10)]
  3. What are lambda functions?
    • Lambda functions are anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. Example:
    add = lambda x, y: x + y
  4. What is the difference between deepcopy and shallow copy?
    • A shallow copy creates a new object but inserts references into it to the objects found in the original. A deep copy creates a new object and recursively copies all objects found in the original, ensuring no shared references.
  5. What is the purpose of the __init__ method in Python?
    • The __init__ method is a constructor method used to initialize an instance of a class. It is called automatically when a new instance is created.
  6. How do you manage packages in Python?
    • Packages are managed using pip, the Python package installer. You can install packages using commands like pip install package_name and create isolated environments using virtualenv or venv.
  7. What are decorators in Python?
    • Decorators are functions that modify or extend the behavior of other functions or methods. They are applied using the @decorator_name syntax.
  8. Explain the with statement in Python.
    • The with statement simplifies exception handling by encapsulating setup and cleanup actions within context managers. Example:
    with open('file.txt', 'r') as file: data = file.read()
  9. What is a generator in Python?
    • Generators are functions that yield items one at a time and are used to create iterators. They use the yield keyword to produce values lazily. Example:
    def count_up_to(max): count = 1 while count <= max: yield count count += 1
  10. What are Python’s built-in functions?
    • Built-in functions include len(), type(), range(), map(), filter(), sorted(), sum(), and abs(), among others.

Advanced Questions

  1. What is the Global Interpreter Lock (GIL) in Python?
    • The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes simultaneously. This can be a limitation for CPU-bound multi-threaded programs.
  2. How does Python handle memory management?
    • Python uses automatic memory management with reference counting and cyclic garbage collection. It deallocates memory for objects that are no longer referenced.
  3. What are Python’s built-in modules?
    • Built-in modules include math, datetime, os, sys, json, re, random, collections, and many others.
  4. What is the difference between @staticmethod and @classmethod?
    • @staticmethod defines a method that does not operate on an instance or class. @classmethod defines a method that operates on the class itself and receives the class as its first argument.
  5. What are metaclasses in Python?
    • Metaclasses are classes of classes that define how classes behave. They are used to create and customize class behaviors and can be defined by inheriting from type.
  6. Explain Python’s garbage collection mechanism.
    • Python uses reference counting and cyclic garbage collection to manage memory. Reference counting keeps track of the number of references to an object, and cyclic garbage collection detects and collects cyclic references that cannot be reached by reference counting alone.
  7. What are Python’s built-in data structures?
    • Built-in data structures include list, tuple, dict, set, and frozenset. These structures support various operations and offer different performance characteristics.
  8. How do you create a virtual environment in Python?
    • Virtual environments are created using venv or virtualenv. Example:
    python -m venv myenv
  9. What is the difference between __str__ and __repr__?
    • __str__ is used to create a readable string representation of an object for end-users. __repr__ is used to create an unambiguous string representation that can be used for debugging and development.
  10. What are context managers and how do you use them?
    • Context managers are used to manage resources, ensuring that setup and cleanup are handled properly. They are used with the with statement to ensure that resources are released correctly. Example:
      python with open('file.txt', 'r') as file: data = file.read()

Expert Questions

  1. How do you optimize Python code for performance?
    • Optimize performance by using efficient algorithms, profiling code to identify bottlenecks, utilizing built-in functions, avoiding unnecessary computations, and using libraries like NumPy for intensive numerical operations.
  2. Explain the concept of monkey patching.
    • Monkey patching involves dynamically modifying or extending a class or module at runtime. It allows for changes to existing code without modifying the original source.
  3. What are the differences between Python 2 and Python 3?
    • Key differences include print statements (Python 2: print "text", Python 3: print("text")), integer division (Python 2: 5 / 2 == 2, Python 3: 5 / 2 == 2.5), Unicode handling, and changes in standard library modules.
  4. What is the __getitem__ method?
    • The __getitem__ method allows a class to define how it should respond to indexing operations, e.g., obj[key].
  5. How do you handle memory leaks in Python?
    • Handle memory leaks by analyzing memory usage with tools like tracemalloc, using weak references for objects with cyclic dependencies, and ensuring that objects are properly de-referenced.
  6. What are Python’s async and await keywords used for?
    • async and await are used to write asynchronous code. async defines an asynchronous function, and await is used to pause the function until an awaitable object is resolved.
  7. Explain the concept of duck typing in Python.
    • Duck typing refers to the practice of determining an object’s suitability based on its behavior (methods and properties) rather than its explicit type. If an object behaves like a duck, it is treated as a duck.
  8. **What is the use of `slots

in a class definition?** -__slots__` restricts the attributes of a class to a fixed set, saving memory by avoiding the creation of a dynamic attribute dictionary.

  1. How do you perform unit testing in Python?
    • Unit testing is performed using the unittest module. You define test cases by subclassing unittest.TestCase and use methods like assertEqual to verify that the code behaves as expected. Example:
    import unittest class TestMyFunction(unittest.TestCase): def test_add(self): self.assertEqual(add(1, 2), 3)
  2. What are Python’s __iter__ and __next__ methods used for?
    • __iter__ is used to return an iterator object, and __next__ is used to return the next item from the iterator. Together, they allow a class to be iterable.
  3. What are the benefits of using Python’s collections module?
    • The collections module provides specialized data structures like namedtuple, deque, Counter, and OrderedDict, which offer additional functionality and efficiency compared to built-in types.
  4. What is a closure in Python?
    • A closure is a function that retains access to the variables from its lexical scope even after the function has finished executing. This allows the inner function to remember and access those variables.
  5. What are some common Python design patterns?
    • Common design patterns in Python include Singleton, Factory, Observer, Strategy, and Decorator patterns. Each pattern addresses specific design problems and provides reusable solutions.
  6. Explain the concept of monkey patching in Python.
    • Monkey patching allows you to modify or extend existing classes or modules at runtime. It is typically used to alter behavior without changing the original codebase. Example:
    import some_module def new_method(self): return 'Modified method' some_module.SomeClass.old_method = new_method
  7. How do you handle file I/O operations in Python?
    • File I/O operations are handled using built-in functions like open(), with file objects supporting methods such as read(), write(), and close(). Example:
    with open('file.txt', 'w') as file: file.write('Hello, World!')
  8. What is the difference between is and == in Python?
    • is checks for object identity (whether two references point to the same object in memory), while == checks for equality of values (whether the values of two objects are equal).
  9. How do you implement inheritance in Python?
    • Inheritance is implemented by creating a new class that derives from an existing class. The derived class inherits attributes and methods from the base class. Example:
    class Animal: def speak(self): pass class Dog(Animal): def speak(self): return 'Woof'
  10. What is the __call__ method in Python?
    • The __call__ method allows an instance of a class to be called as if it were a function. This is useful for creating callable objects.
  11. What are args and kwargs in function definitions?
    • *args allows a function to accept a variable number of positional arguments, while **kwargs allows it to accept a variable number of keyword arguments. Example:
    def func(*args, **kwargs): print(args) print(kwargs)
  12. How do you use the zip() function in Python?
    • The zip() function combines multiple iterables element-wise into tuples. Example:
      python names = ['Alice', 'Bob', 'Charlie'] scores = [85, 90, 88] combined = zip(names, scores) # [('Alice', 85), ('Bob', 90), ('Charlie', 88)]

Exit mobile version