Interview Questions

1) Explain the difference between deepcopy() and copy() in Python.


  • copy(): Creates a shallow copy of the object, meaning if the object contains nested objects, only references to those objects are copied.
  • deepcopy(): Creates a deep copy of the object, recursively copying all nested objects, so the original and copied objects are completely independent.

2) What is Python?


Python is a high-level, interpreted, and general-purpose programming language. It emphasizes code readability with its use of significant indentation. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

3) What are the key features of Python?


  • Simple and easy-to-read syntax
  • Interpreted language
  • Dynamically typed
  • Object-oriented
  • Extensive standard libraries
  • Cross-platform
  • Supports both high-level and low-level programming

4) What are Python's data types?


Python includes several built-in data types:

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

5) What is the difference between a list and a tuple?


  • List: Mutable (can be modified after creation), defined using square brackets [].
  • Tuple: Immutable (cannot be modified after creation), defined using parentheses ().

6) What are Python decorators?


Decorators in Python are a way to modify or enhance the functionality of functions or methods without changing their actual code. They are applied with the @decorator_name syntax and are often used for logging, access control, caching, etc.

7) What is the difference between is and == in Python?


  • == checks for value equality (whether two objects have the same value).
  • is checks for identity equality (whether two objects are the same in memory).

8) What is a Python generator?


A generator is a function that returns an iterator, allowing you to iterate over data without storing the entire data in memory. It is defined using the yield keyword.

9) What is the use of self in Python classes?


self represents the instance of the class. It allows access to the instance’s attributes and methods. It must be the first parameter in every method defined in a class.

10) What is the difference between __str__() and __repr__()?


  • __str__() is used to define the "informal" string representation of an object, primarily used for human-readable output.
  • __repr__() is used to define the "formal" string representation, often used for debugging or in the Python shell. Ideally, __repr__() should return a string that can be used to recreate the object.

11) What is list comprehension?


List comprehension provides a concise way to create lists by applying an expression to each element in an iterable.

Example:

squares = [x**2 for x in range(10)]

 

12) What are Python modules and packages?


  • Module: A file containing Python code (functions, variables, classes). Example: math.py is a module.
  • Package: A collection of modules. A package is a directory that contains a special __init__.py file.

13) What is the difference between range() and xrange()?


  • range() returns a list in Python 2.x and a generator in Python 3.x.
  • xrange() only exists in Python 2.x and behaves like range() in Python 3.x (i.e., it returns a generator-like object).

14) What is Python's Global Interpreter Lock (GIL)?


The GIL is a mutex that allows only one thread to execute Python bytecode at a time, even in multi-threaded programs. This can be a bottleneck for CPU-bound tasks but doesn't affect I/O-bound tasks much.

15) Explain the use of with statement in Python.


The with statement simplifies exception handling and resource management, ensuring that resources (e.g., files) are properly cleaned up after use. It is commonly used for working with files:

with open('file.txt', 'r') as file:
    content = file.read()

 

16) What are the differences between Python 2.x and Python 3.x?


  • Print function: print is a function in Python 3 (print()) and a statement in Python 2.
  • Integer division: In Python 3, division of integers returns a float (5/2 == 2.5), while in Python 2, it returns an integer (5/2 == 2).
  • Unicode strings: In Python 3, strings are Unicode by default.

17) What is the pass statement in Python?


The pass statement is a placeholder that does nothing. It’s used where syntactically some code is required but you don't want to execute anything.

Example:

def empty_function():
    pass

 

18) What is the yield keyword in Python?


The yield keyword is used in a function to return a generator. Instead of returning a value and exiting, yield returns a value and suspends the function’s state, allowing it to resume where it left off when the next value is requested.

19) How can you handle exceptions in Python?


You can handle exceptions using the try and except blocks:

try:
    # code that might throw an exception
except SomeException as e:
    # code to handle the exception

 

20) What are Python's built-in data structures?


Python's built-in data structures include:

  • List: Ordered, mutable collection of items.
  • Tuple: Ordered, immutable collection of items.
  • Set: Unordered collection of unique items.
  • Dictionary: Unordered collection of key-value pairs.

21) What are Python iterators?


An iterator is an object that can be iterated upon, meaning that it has a __next__() method that returns the next value in the sequence. Iterators must implement two methods: __iter__() and __next__().

22) Explain the concept of closures in Python.


A closure is a function that captures the variables from its enclosing scope even after the outer function has finished executing.

Example:

def outer(x):
    def inner(y):
        return x + y
    return inner
add_five = outer(5)
print(add_five(3))  # Output: 8

 

23) What are Python's built-in functions?


Some common built-in functions in Python include:

  • len(), max(), min(), sorted(), sum(), input(), type(), range(), str(), etc.

24) What is the difference between sort() and sorted()?


  • sort() modifies the list in place and doesn’t return a value.
  • sorted() returns a new sorted list and does not modify the original list.

25) What is an abstract class in Python?


An abstract class is a class that cannot be instantiated directly. It can contain abstract methods that must be implemented by subclasses. It is defined using the abc module.

Example:

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

 

26) What is the difference between del and remove()?


  • del: Deletes an item at a specific index or deletes an entire object.
  • remove(): Removes the first occurrence of a specified value from a list.

27) What are Python's file modes?


Common file modes include:

  • 'r' – read
  • 'w' – write
  • 'a' – append
  • 'b' – binary (e.g., rb for reading binary files)

28) What is the purpose of __init__() in Python?


__init__() is the constructor method in Python classes. It is automatically called when a new object is created and initializes the object’s attributes.

29) How can you improve the performance of Python code?


  • Use list comprehensions instead of loops where possible.
  • Avoid using global variables.
  • Use generators instead of lists for large data sets.
  • Profile the code using tools like cProfile.
  • Optimize algorithms and data structures.

 


 

This list covers a wide range of topics to help you get ready for your Python interview. Best of luck!

30) What is a Python lambda function?


A lambda function is an anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression.

Example:

square = lambda x: x**2