Python:Top Interview Questions and Answers

Top 50 Python Interview Questions and Answers

Top 50 Python Interview Questions and Answers

1. What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms including procedural, object-oriented, and functional programming. Python is widely used for web development, data analysis, artificial intelligence, automation, and more due to its vast ecosystem of libraries and frameworks.

2. What are the key features of Python?

  • Easy to Learn: Simple syntax resembling English.
  • Interpreted Language: Executes line-by-line, making debugging easier.
  • Dynamically Typed: No need to declare data types explicitly.
  • Extensive Libraries: Rich set of modules and packages.
  • Portable: Can run on various platforms without modification.
  • Object-Oriented: Supports encapsulation, inheritance, and polymorphism.

3. What is the difference between list and tuple?

Lists are mutable, meaning their elements can be changed after creation, while tuples are immutable and cannot be changed once defined. Lists are defined using square brackets [], and tuples using parentheses ().

# List example (mutable)
my_list = [1, 2, 3]
my_list[0] = 10  # Modifying element at index 0

# Tuple example (immutable)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # This would raise a TypeError

4. How is memory managed in Python?

Python uses a combination of reference counting and garbage collection for memory management. Every object in Python maintains a reference count which tracks how many references point to the object. When this count drops to zero, the memory is automatically reclaimed. Python also includes a cyclic garbage collector to clean up reference cycles (objects referencing each other).

5. What are Python's built-in data types? Provide examples of each.

Explanation: Python has several built-in data types that can be categorized as:

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

Example:

# Example of Python data types
      x = 10  # int
      y = 3.14  # float
      z = "Hello"  # str
      a = [1, 2, 3]  # list
      b = (1, 2, 3)  # tuple
      c = {1, 2, 3}  # set
      d = {"key": "value"}  # dict
      e = True  # bool
      

6. What is a dictionary in Python?

A dictionary is an unordered, mutable collection of items that stores data in key-value pairs. Keys must be unique and immutable, whereas values can be any data type.

# Creating a dictionary
my_dict = {"name": "Alice", "age": 25}

# Accessing value by key
print(my_dict["name"])  # Output: Alice

7. What is PEP 8?

PEP 8 is the Python Enhancement Proposal which provides guidelines and best practices on how to write Python code. It promotes code readability and uniformity across Python scripts by defining standards like indentation, naming conventions, line length, etc.

8. How do you handle exceptions in Python?

Python provides a mechanism to handle errors using try, except, else, and finally blocks to prevent programs from crashing.

try:
    result = 10 / 0  # Division by zero
except ZeroDivisionError:
    print("Cannot divide by zero")  # Exception handler
else:
    print("No error occurred")  # Executes if no exception
finally:
    print("Execution complete")  # Executes regardless of exception

9. What is the use of the 'self' keyword?

self refers to the instance of the class and is used to access variables and methods associated with the object. It must be the first parameter in instance methods.

class Person:
    def __init__(self, name):
        self.name = name  # Assigns the name to the instance variable

    def greet(self):
        print("Hello, my name is", self.name)

10. What are *args and **kwargs in Python?

Explanation: In Python, *args and **kwargs are used to pass a variable number of arguments to a function. *args allows a function to accept any number of positional arguments, while **kwargs allows for any number of keyword arguments.

Example:

# Example of *args and **kwargs
      def my_function(*args, **kwargs):
          print("Positional arguments:", args)
          print("Keyword arguments:", kwargs)

      my_function(1, 2, 3, name="John", age=30)
      # Output:
      # Positional arguments: (1, 2, 3)
      # Keyword arguments: {'name': 'John', 'age': 30}
      

11. What is the difference between deep copy and shallow copy in Python?

Explanation: A shallow copy creates a new object but does not create copies of the objects inside it. In contrast, a deep copy creates a new object and recursively copies all objects inside it. Shallow copies can lead to issues when modifying nested objects, whereas deep copies do not.

Example:

# Example of shallow and deep copy
      import copy

      original_list = [1, 2, [3, 4]]
      shallow_copy = copy.copy(original_list)
      deep_copy = copy.deepcopy(original_list)

      original_list[2][0] = 99

      print("Original List:", original_list)   # Output: [1, 2, [99, 4]]
      print("Shallow Copy:", shallow_copy)     # Output: [1, 2, [99, 4]]
      print("Deep Copy:", deep_copy)           # Output: [1, 2, [3, 4]]
      

12. What are lambda functions in Python? Provide an example.

Explanation: A lambda function in Python is an anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one expression. Lambda functions are often used for short, throwaway functions, such as in higher-order functions like map(), filter(), and reduce().

Example:

# Example of lambda function
    add = lambda x, y: x + y
    print(add(3, 4))  # Output: 7
    

13. What are the key differences between lists and tuples in Python?

Explanation: Lists are mutable, meaning you can change their content (add, remove, or modify items), while tuples are immutable. Lists use [] and tuples use ().

# List (mutable)
my_list = [1, 2, 3]
my_list[0] = 10

# Tuple (immutable)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # This will raise a TypeError

14. What is the difference between is and == in Python?

Explanation: The == operator compares the values of two objects, while the is operator compares the memory locations of two objects (i.e., whether they are the same object in memory).

Example:

# Example of "is" vs "=="
      a = [1, 2, 3]
      b = [1, 2, 3]

      print(a == b)  # Output: True (because their values are the same)
      print(a is b)  # Output: False (because they are two different objects in memory)
      

15. What is the purpose of the pass statement?

pass is a null statement in Python. It acts as a placeholder where syntactically some code is required but no action is needed.

def function():
    pass  # To be implemented later

16. What is __init__.py used for?

__init__.py is used to mark a directory as a Python package. It can be empty or execute initialization code for the package.

17. What is the difference between Python 2 and Python 3?

  • Print statement: Python 2 uses print, Python 3 uses print()
  • Integer division: Python 2 truncates, Python 3 returns float
  • Unicode: Default in Python 3
  • Library support: Python 2 is deprecated

18. What are Python iterators?

Iterators are objects in Python that implement the __iter__() and __next__() methods. They allow iteration over a sequence one element at a time.

my_list = [1, 2, 3]
iterator = iter(my_list)

print(next(iterator))  # Output: 1
print(next(iterator))  # Output: 2
print(next(iterator))  # Output: 3

19. What is the difference between @staticmethod and @classmethod?

Explanation: @staticmethod defines a method that doesn't operate on an instance of the class. It is bound to the class rather than the instance. @classmethod, on the other hand, defines a method that operates on the class itself and takes the class as the first argument (usually named cls).

Example:

# Example of @staticmethod and @classmethod
class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method")

    @classmethod
    def class_method(cls):
        print(f"This is a class method of {cls.__name__}")

obj = MyClass()
obj.static_method()   # Output: This is a static method
obj.class_method()    # Output: This is a class method of MyClass

20. What is the use of super() in Python?

Explanation: The super() function is used to call a method from a parent class. It is typically used in a subclass to invoke the parent class’s methods, especially in cases of multiple inheritance, to ensure the correct method is called without needing to explicitly reference the parent class.

Example:

# Example using super() to call parent class method
    class A:
        def method(self):
            print("Method in class A")

    class B(A):
        def method(self):
            print("Method in class B")
            super().method()  # Calling method from class A

    # Creating an object of class B
    b = B()
    b.method()  # This will call method from B, then from A using super()

21. How does Python implement multiple inheritance? What is the method resolution order (MRO)?

Explanation: Python supports multiple inheritance, meaning a class can inherit from more than one parent class. The method resolution order (MRO) determines the order in which classes are searched for methods. Python uses the C3 linearization algorithm to ensure a consistent and predictable search order when multiple base classes are involved.

Example:

# Example demonstrating multiple inheritance and MRO
    class A:
        def method(self):
            print("Method from class A")

    class B(A):
        def method(self):
            print("Method from class B")

    class C(A):
        def method(self):
            print("Method from class C")

    class D(B, C):
        pass

    # Creating an object of class D
    d = D()
    d.method()  # Will call the method from class B due to MRO
    print(D.__mro__)  # Displays the MRO (Method Resolution Order)

22. What are decorators in Python?

Decorators are functions that modify the behavior of other functions. They are used to add functionality to an existing function without changing its code.

def decorator(func):
        def wrapper():
            print("Before function call")
            func()
            print("After function call")
        return wrapper

    @decorator
    def say_hello():
        print("Hello!")

    say_hello()  # Output: Before function call, Hello!, After function call
    

23. What is multithreading in Python? How does the Global Interpreter Lock (GIL) affect it?

Explanation: Multithreading allows multiple threads to run concurrently within a process. However, Python’s GIL allows only one thread to execute Python bytecode at a time, limiting true parallelism in CPU-bound tasks. It is better suited for I/O-bound operations.

import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()

24. What is the difference between import, from ... import, and import ... as?

Explanation:

  • import module: Imports the whole module.
  • from module import func: Imports a specific function or variable.
  • import module as alias: Imports the module and gives it an alias.
import math
print(math.sqrt(16))

from math import sqrt
print(sqrt(25))

import math as m
print(m.pow(2, 3))

25. What is the purpose of the pass statement in Python?

The pass statement is a placeholder used when a statement is required syntactically but you don’t want to execute any code.

def function_with_no_implementation():
        pass  # No operation, placeholder
    

26. What is the purpose of the map() function in Python? Provide an example.

Explanation: The map() function applies a given function to all the items in an iterable (like a list) and returns an iterator that yields the results. It is commonly used for applying transformations to elements in a list.

Example:

# Example of map function
    numbers = [1, 2, 3, 4]
    squared = map(lambda x: x ** 2, numbers)
    print(list(squared))  # Output: [1, 4, 9, 16]
    

27. What is the purpose of the __init__ method in Python?

Explanation: The __init__ method is the constructor in Python. It is automatically called when a new object of a class is instantiated. This method is typically used to initialize the attributes of the new object.

Example:

# Example of __init__ method
  class Person:
      def __init__(self, name, age):
          self.name = name
          self.age = age

  person1 = Person("Alice", 30)
  print(person1.name)  # Output: Alice
  print(person1.age)   # Output: 30
  

28. What are the different types of inheritance in Python?

Explanation: Python supports several types of inheritance, including:

  • Single Inheritance: A class inherits from one parent class.
  • Multiple Inheritance: A class inherits from multiple parent classes.
  • Multilevel Inheritance: A class inherits from a class that is derived from another class.
  • Hierarchical Inheritance: Multiple classes inherit from a single parent class.
  • Hybrid Inheritance: A combination of two or more types of inheritance.

Example:

# Example of multiple inheritance
    class A:
        def speak(self):
            print("Speaking from class A")

    class B:
        def walk(self):
            print("Walking from class B")

    class C(A, B):
        pass

    obj = C()
    obj.speak()  # Output: Speaking from class A
    obj.walk()   # Output: Walking from class B
    

29. What is the purpose of the global keyword in Python?

Explanation: The global keyword is used to declare a variable as global inside a function. This allows the function to modify the variable defined outside its scope, rather than creating a local variable with the same name.

Example:

# Example of global keyword
  x = 10

  def modify_global():
      global x
      x = 20

  modify_global()
  print(x)  # Output: 20
  

30. What is the difference between a module and a package in Python?

Explanation: In Python, a module is a single file containing Python code, such as functions, classes, and variables. A package is a collection of modules grouped together in a directory. A package may also contain sub-packages, and it typically includes an __init__.py file that marks it as a package directory.

Example:

# Example of a module
    # mymodule.py
    def greet(name):
        return f"Hello, {name}!"

    # Example of a package structure
    # mypackage/
    #     __init__.py
    #     module1.py
    #     module2.py
    

Usage:

# Importing a module
    import mymodule
    print(mymodule.greet("Alice"))

    # Importing from a package
    from mypackage import module1
    

31. How do sets differ from lists in Python?

Explanation: Sets are unordered, do not allow duplicate elements, and provide faster membership testing. Lists are ordered and allow duplicates.

my_list = [1, 2, 2, 3]
print(my_list)  # [1, 2, 2, 3]

my_set = {1, 2, 2, 3}
print(my_set)   # {1, 2, 3}

32. How can you merge two dictionaries in Python?

Explanation: You can merge two dictionaries in Python using the update() method or the ** unpacking operator. The update() method adds the key-value pairs from the second dictionary to the first one, and the unpacking operator allows merging dictionaries into a new dictionary.

Example:

# Example of merging dictionaries
    dict1 = {'a': 1, 'b': 2}
    dict2 = {'c': 3, 'd': 4}

    # Using update()
    dict1.update(dict2)
    print(dict1)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

    # Using unpacking operator
    merged_dict = {**dict1, **dict2}
    print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    

33. How do you read and write files in Python?

Explanation: In Python, files can be read and written using built-in functions like open(), which returns a file object. You can open a file in various modes like r for reading, w for writing, a for appending, etc. Once the operations are done, the file should be closed using close() to ensure that changes are saved and resources are freed.

Example:

# Reading a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, world!")

# Appending to a file
with open('example.txt', 'a') as file:
    file.write("\nAppended text.")

# Note: Using 'with' automatically closes the file after the block is executed.

34. What is the purpose of the __del__ method in Python?

Explanation: The __del__ method is a destructor in Python. It is automatically called when an object is about to be destroyed. It is used to clean up resources such as closing files or network connections.

Example:

# Example of __del__ method
class MyClass:
    def __init__(self):
        print("Object created")
    
    def __del__(self):
        print("Object destroyed")

obj = MyClass()  # Output: Object created
del obj          # Output: Object destroyed

35. What is a list comprehension in Python? Provide an example.

Explanation: List comprehensions provide a concise way to create lists in Python. They consist of an expression followed by a for clause and optionally an if condition. List comprehensions are more compact and efficient compared to traditional for loops for creating lists.

Example:

# Example of list comprehension
    numbers = [1, 2, 3, 4, 5]
    squared_numbers = [x ** 2 for x in numbers if x % 2 == 0]
    print(squared_numbers)  # Output: [4, 16]
    

36. How do you reverse a string in Python?

You can reverse a string in Python using slicing with a negative step value.

string = "hello"
    reversed_string = string[::-1]
    print(reversed_string)  # Output: "olleh"
    

37. What is the purpose of the zip function in Python?

The zip() function combines two or more iterables into a single iterator of tuples. It is often used to pair corresponding elements from multiple sequences.

names = ["Alice", "Bob"]
        ages = [25, 30]
        zipped = zip(names, ages)
        print(list(zipped))  # Output: [('Alice', 25), ('Bob', 30)]
    

38. What is the global interpreter lock (GIL) in Python?

The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This can limit multi-threading performance in CPython.

39. How do you create a virtual environment in Python?

Explanation: A virtual environment in Python is created using the venv module. Virtual environments are used to isolate dependencies for different projects, allowing you to install specific package versions without affecting other projects.

Steps:

# Step 1: Create a virtual environment
    python -m venv myenv

    # Step 2: Activate the virtual environment
    # On Windows:
    myenv\Scripts\activate
    # On macOS/Linux:
    source myenv/bin/activate

    # Step 3: Install packages (optional)
    pip install 

    # Step 4: Deactivate the virtual environment when done
    deactivate
    

40. What are Python iterators and how do they work?

Iterators are objects that implement the __iter__() and __next__() methods, allowing them to iterate over a collection. You can create custom iterators by defining these methods in a class.

class Countdown:
        def __init__(self, start):
            self.start = start

        def __iter__(self):
            return self

        def __next__(self):
            if self.start <= 0:
                raise StopIteration
            self.start -= 1
            return self.start

    countdown = Countdown(5)
    for number in countdown:
        print(number)
    

41. What is a context manager in Python? Provide an example of using with statement.

Explanation: A context manager in Python is an object that manages the setup and cleanup of resources using the with statement. The context manager ensures that resources like file handles are properly opened and closed, even if an exception occurs.

Example:

# Example of using a context manager with "with" statement
    with open("example.txt", "w") as file:
        file.write("Hello, world!")

    # The file is automatically closed when the block of code ends.
    

42. What is the difference between binary and text file modes in Python?

Explanation: Text mode ('t') is the default and handles the file as a string. Binary mode ('b') reads or writes the file as bytes. Binary mode is typically used for non-text files like images, videos, or executables.

# Reading a text file
    with open('sample.txt', 'rt') as f:
        text = f.read()

    # Reading a binary file (e.g., image)
    with open('image.png', 'rb') as f:
        data = f.read()

43. What are regular expressions in Python?

Regular expressions are patterns used to match strings. The re module in Python provides functions to search, match, and replace strings using regular expressions.

import re
    pattern = r"\d+"  # Matches one or more digits
    result = re.findall(pattern, "There are 123 apples")
    print(result)  # Output: ['123']
    

44. What is the difference between append() and extend() in Python?

append() adds a single element to a list, while extend() adds elements from an iterable to the list.

lst = [1, 2]
    lst.append(3)  # [1, 2, 3]
    lst.extend([4, 5])  # [1, 2, 3, 4, 5]
    

45. How do you perform object serialization in Python?

Object serialization is done using the pickle module, which allows you to save Python objects to a file and load them later.

import pickle
    data = {'name': 'Alice', 'age': 30}
    with open('data.pkl', 'wb') as file:
        pickle.dump(data, file)
    

46. What is the difference between __str__ and __repr__ in Python?

Explanation: The __str__ method is used to define a string representation of an object that is easy for humans to read, whereas __repr__ is used to define a string representation that is more precise and can be used to recreate the object.

Example:

# Example of __str__ and __repr__
    class MyClass:
        def __str__(self):
            return "This is a user-friendly string."

        def __repr__(self):
            return "MyClass()"

    obj = MyClass()
    print(str(obj))   # Output: This is a user-friendly string.
    print(repr(obj))  # Output: MyClass()
    

47. How do you sort a list in Python?

Use the sort() method to sort a list in place, or the sorted() function to return a new sorted list.

lst = [3, 1, 2]
    lst.sort()  # Modifies lst to [1, 2, 3]
    new_lst = sorted(lst)  # Returns a new sorted list [1, 2, 3]
    

48. How can you remove duplicates from a list in Python?

To remove duplicates, convert the list to a set, then back to a list. Sets do not allow duplicate values.

lst = [1, 2, 2, 3, 4, 4]
    lst = list(set(lst))
    print(lst)  # Output: [1, 2, 3, 4]
    

49. What is list slicing in Python?

List slicing allows extracting a portion of a list using the [start:end] syntax. It returns a new list with the elements from start to end (not including end).

lst = [0, 1, 2, 3, 4]
    sublist = lst[1:4]
    print(sublist)  # Output: [1, 2, 3]
    

50. How do you merge two lists in Python?

You can merge two lists using the + operator or the extend() method.

list1 = [1, 2]
    list2 = [3, 4]
    merged = list1 + list2  # [1, 2, 3, 4]
    list1.extend(list2)  # [1, 2, 3, 4]
    

Comments