Top Python Interview Questions



1) What are the key features of Python?

  • Easy to Learn: Python is simple and easy to read.
  • Line-by-Line Execution: Makes finding errors easier.
  • No Type Declarations: Python decides variable types automatically.
  • Handles Complexity: Takes care of memory and other tough tasks for you.
  • Built-In Tools: Has many ready-made features to help you.
  • Works Everywhere: Runs on any computer system.
  • Flexible Coding: Supports different ways of writing programs.


2) What is the difference between list and tuple in Python?

  • Mutability:
    • List: Mutable (can be modified after creation).
    • Tuple: Immutable (cannot be modified after creation).
  • Syntax:
    • List: Defined using square brackets [].
    • Tuple: Defined using parentheses ().
  • Performance:
    • List: Slower for iteration and modification due to its mutability.
    • Tuple: Faster because of its immutability.

Example:

# List
        my_list = [1, 2, 3]
        my_list[0] = 5 # Can modify

        # Tuple
        my_tuple = (1, 2, 3)
        # my_tuple[0] = 5 # Raises TypeError as tuple is immutable

3) What are Python decorators, and how do they work?

        Decorators are functions that modify the behavior of another function or method.         They are applied using the @ symbol.

Example:

    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



4) What is the difference between shallow copy and deep copy in Python?

  • Shallow Copy: Copies the reference addresses of nested objects. Changes to nested objects affect the copied object.
  • Deep Copy: Copies the actual objects recursively. Changes to nested objects do not affect the copied object.

Example:

         import copy

         # Shallow copy
        original = [[1, 2], [3, 4]]
        shallow_copied = copy.copy(original)
        shallow_copied[0][0] = 5
        print(original) 
        # Output:   [[5, 2], [3, 4]] (original is affected)

        # Deep copy
        deep_copied = copy.deepcopy(original)
        deep_copied[0][0] = 9
        print(original) 
         # Output: [[5, 2], [3, 4]] (original is not affected)

5) What are Python's built-in data types?

Python's built-in data types include:

  • 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

6) Explain the difference between is and == in Python.

  • is: Checks if two variables point to the same object in memory (identity comparison).
  • ==: Checks if the values of two variables are the same (value comparison).

Example:

        a = [1, 2, 3]
        b = [1, 2, 3]

        print(a == b)  # True, values are the same
        print(a is b)  # False, they are different objects in memory

7) What is a lambda function in Python?

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

Example:

        multiply = lambda x, y: x * y
        print(multiply(2, 3))  
        # Output: 6

8) What are Python generators?

Generators are functions that yield items one at a time using the yield keyword. They provide an efficient way to handle large datasets without loading everything into memory at once.

Example:

        def count_up_to(limit):
                count = 1
                while count <= limit:
                       yield count
                        count += 1

        counter = count_up_to(5)
        for number in counter:
                print(number)

9) What are Python modules and packages?

  • Module: A file containing Python code, which can define functions, classes, and variables.
  • Package: A directory containing multiple modules and a special __init__.py file to indicate it is a package.

Example:

  • math is a built-in module.
  • A package might be a folder structure with multiple .py files.

10) How do you merge two dictionaries in Python?

You can merge two dictionaries using the update() method or the ** unpacking operator or in Python 3.9 and later, use the | operator

Example:

        dict1 = {'a': 1, 'b': 2}
        dict2 = {'b': 3, 'c': 4}

       dict1.update(dict2)  
       # Output: {'a': 1, 'b': 3, 'c': 4}
                                    OR
        merged_dict = {**dict1, **dict2} 
        print(dict1)  
        # Output: {'a': 1, 'b': 3, 'c': 4}
                                    OR
        merged = dict1 | dict2
        print(merged)  
        # Output: {'a': 1, 'b': 3, 'c': 4}

11) What are Python's mutable and immutable types?

  • Mutable types: Objects whose value can be changed after creation 
          Example: list, dict, set
  • Immutable types: Objects whose value cannot be changed after creation.
          Example: tuple, str, int

12) Explain the concept of slicing in Python

Slicing allows you to extract parts of a sequence (e.g., list, tuple, string) by specifying a start, stop, and step.

Example:

        my_list = [0, 1, 2, 3, 4, 5]
        print(my_list[1:4])  
            # Output: [1, 2, 3]
        print(my_list[:3])   
            # Output: [0, 1, 2]
        print(my_list[::2]) 
            # Output: [0, 2, 4]

13) What is the purpose of the Self keyword in Python?

The self keyword is used to refer to the instance of the class in object-oriented programming. It is used to access instance variables and methods within a class.

Example:

        class MyClass:
            def __init__(self, name):
                    self.name = name
            def greet(self):
                   print(f"Hello, {self.name}")

        obj = MyClass("pythonbuzz")
        obj.greet()  
         # Output: Hello, pythonbuzz

14) How do you handle exceptions in Python?

Exceptions are handled using try, except, and optionally else and finally.

Example:

        try:
            result = 10 / 0
        except ZeroDivisionError:
            print("Cannot divide by zero!")
        else:
            print("No errors!")
        finally:
            print("This will always execute.")

15) What is the difference between del and remove() in Python?

  • del: Deletes a variable or a specific index/item from a list.
  • remove(): Removes the first occurrence of a value from a list.

Example:

        my_list = [1, 2, 3, 4]
        del my_list[1]  # Deletes element at index 1
        # Output: my_list = [1, 3, 4]
        my_list.remove(3)  # Removes element with value 3
        # Output:my_list = [1, 4]

16) What is the purpose of the with statement in Python?

The with statement is used to wrap the execution of a block of code. It simplifies exception handling and ensures resources are properly cleaned up (e.g., closing a file after use).

Example:

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

17) Explain Python's map() function.

The map() function applies a given function to each item of an iterable (list, tuple, etc.) and returns a map object (an iterator).

Example:

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

18) What is list comprehension in Python?

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

Example:

        numbers = [1, 2, 3, 4]
        squared = [x ** 2 for x in numbers]
        print(squared) 
        # Output: [1, 4, 9, 16]

19) What is a Python iterator and how do you create one?

An iterator is an object that lets you loop through values one at a time. To create one, you need to define two methods: __iter__() and __next__().

Example:

class MyIterator:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.limit:
            self.current += 1
            return self.current
        else:
            raise StopIteration

# Create an iterator
iterator = MyIterator(3)

# Loop through the iterator
for num in iterator:
    print(num)
#output:
1
2
3

20) How does Python support object-oriented programming?

Python supports object-oriented programming (OOP) with the concepts of classes, objects, inheritance, polymorphism, encapsulation, and abstraction.

Example:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    def speak(self):
        print(f"{self.name} barks")

dog = Dog("Buddy")
dog.speak()  # Output: Buddy barks

21)What are Python's data structures?

Python has the following built-in data structures:

  • List: Ordered, mutable, and allows duplicates.
         Example: [1, 2, 3]
  • Tuple: Ordered, immutable, and allows duplicates. Example: (1, 2, 3)
  • Set: Unordered, mutable, and does not allow duplicates. Example: {1, 2, 3}
  • Dictionary: Unordered, mutable, and stores key-value pairs. Example: {'a': 1, 'b': 2}
22)What are Python's scope rules?

Python follows the LEGB rule to determine the scope of a variable:

  • L: Local — Variables defined inside the current function.

  • E: Enclosing — Variables in the enclosing function.

  • G: Global — Variables defined at the top level of a module.

  • B: Built-in — Variables provided by Python (e.g., print, len).

Example:
x = 10 # Global scope def outer(): y = 5 # Enclosing scope def inner(): z = 2 # Local scope print(x, y, z) inner() outer()
23)What is the difference between args and kwargs in Python?
  • *args: Allows a function to accept a variable number of positional arguments.

  • **kwargs: Allows a function to accept a variable number of keyword arguments.

Example:
        def demo_function(*args, **kwargs):         print("Positional arguments:", args)         print("Keyword arguments:", kwargs)         demo_function(1, 2, 3, name="Alice", age=30)

        # Output:         # Positional arguments: (1, 2, 3)         # Keyword arguments: {'name': 'Alice', 'age': 30}
24)What is the purpose of Python's zip() function?

The zip() function combines multiple iterables into tuples, creating a single iterator.

Example:

        names = ['Rama', 'Sita']         age = [30, 25]         zipped = zip(names, age)         print(list(zipped))

# Output: [('Rama', 30), ('Sita', 25)]

25)Explain Python's enumerate() function.

The enumerate() function adds a counter to an iterable and returns it as an

enumerate object.

Example:

        names = ['Alice', 'Bob']         for index, name in enumerate(names):          print(index, name)

        # Output:            0 Alice             1 Bob

26)What are Python's memory management features?

  • Garbage Collection: Python automatically manages memory using reference

counting and a cyclic garbage collector.

  • Dynamic Memory Allocation: Objects are stored in a private heap managed

by Python.

  • del Keyword: Used to delete references to an object.

Example:
        import gc         x = [1, 2, 3]         del x         gc.collect() # Triggers garbage collection
27)What is the difference between compile-time and runtime
errors in Python?
  • Compile-time errors: Occur when there is an issue in the syntax. Example: print("Hello # Missing closing quote.

  • Runtime errors: Occur while the program is running. Example: Division by zero: 10 / 0

28)What are Python's magic methods?

Magic methods (or dunder methods) are special methods with double underscores

that enable operator overloading and customization.

Example:

class MyClass: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value obj1 = MyClass(10) obj2 = MyClass(20) print(obj1 + obj2) # Output: 30

29)What is the purpose of Python's all() and any() functions?

  • all(): Returns True if all elements in an iterable are true.

  • any(): Returns True if at least one element in an iterable is true.

Example:
        nums = [1, 2, 0]         print(all(nums)) # Output: False         print(any(nums)) # Output: True
30)What is Python's pass statement?

The pass statement is a placeholder used when a statement is syntactically required

but no action is needed.

Example:

        def my_function():          pass

31)How do you check the type of a variable in Python?

Use the type() function to check the type of a variable.

Example:

        x = 42         print(type(x)) # Output: <class 'int'>

32)What are Python's membership operators?

Membership operators (in, not in) test for membership in a sequence

(like a list or string).

Example:

        my_list = [1, 2, 3]         print(2 in my_list) # Output: True         print(4 not in my_list) # Output: True

33) How do you reverse a list in Python?

You can use slicing, the reversed() function, or the .reverse() method.

Example:
        my_list = [1, 2, 3]         print(my_list[::-1]) # Output: [3, 2, 1]
        print(list(reversed(my_list))) # Output: [3, 2, 1]
        my_list.reverse()
        print(my_list) # Output: [3, 2, 1]
34)What are Python's logical operators?

Python has three logical operators: and, or, and not.

Example:

        a = True         b = False         print(a and b) # Output: False         print(a or b) # Output: True         print(not a) # Output: False

35) How do you concatenate strings in Python?

You can concatenate strings using the + operator or the join() method.

Example:

        str1 = "Hello"         str2 = "World"         print(str1 + " " + str2) # Output: Hello World         print(" ".join([str1, str2])) # Output: Hello World

36)What is the difference between break, continue, and pass?
  • break: Exits the loop completely.
  • continue: Skips the current iteration and moves to the next one.
  • pass: Does nothing, just a placeholder.

Example:

for i in range(5): if i == 2: break # Exits loop when i is 2 print(i) for i in range(5): if i == 2: continue # Skips when i is 2 print(i) for i in range(5): if i == 2: pass # Does nothing print(i)

37)How do you handle a file not found error in Python?

Use a try block with exception handling.

Example:

try: with open('non_existent_file.txt', 'r') as file: content = file.read() except FileNotFoundError: print("File not found!")

38)How do you sort a list of dictionaries by a key?

Use the sorted() function with a key parameter.

Example:

data = [{'name': 'John', 'age': 25}, {'name': 'Alice', 'age': 22}] sorted_data = sorted(data, key=lambda x: x['age']) print(sorted_data)

# Output:

[{'name': 'Alice', 'age': 22}, {'name': 'John', 'age': 25}]

39)What is the __name__ == "__main__" construct in Python?

This ensures a script runs only when executed directly, not when imported as a module.

Example:

        if __name__ == "__main__":             print("This runs only when the script is executed directly.")

40)How do you count occurrences of elements in a list?

Use the Counter class from the collections module.

Example:

        from collections import Counter         my_list = [1, 2, 2, 3, 3, 3]         print(Counter(my_list))         # Output: Counter({3: 3, 2: 2, 1: 1})

41)What are Python's set operations?

Sets support operations like union, intersection, difference, and symmetric difference.

Example:

        set1 = {1, 2, 3}         set2 = {3, 4, 5}         print(set1 | set2) # Union: {1, 2, 3, 4, 5}         print(set1 & set2) # Intersection: {3}         print(set1 - set2) # Difference: {1, 2}         print(set1 ^ set2) # Symmetric Difference: {1, 2, 4, 5}

42)What is the eval() function in Python?

The eval() function evaluates a string expression as Python code.

Example:

        x = 5         expression = 'x * 2'         print(eval(expression)) # Output: 10

43)How can you reverse a string in Python?

Using slicing or the reversed() function.

Example:

        # Using slicing         string = "Python"         reversed_string = string[::-1]         print(reversed_string) # Output: nohtyP         # Using reversed()         print(''.join(reversed(string))) # Output: nohtyP

44)What are Python's comprehensions, and why are they used?

Comprehensions provide a concise way to create lists, sets, and dictionaries.

Examples:

        # List comprehension         squares = [x**2 for x in range(5)]         # Set comprehension         unique = {x for x in 'hello'}         # Dictionary comprehension         squared_dict = {x: x**2 for x in range(5)}

45)What is the difference between mutable and immutable
types in Python?
  • Mutable: Can be modified after creation (e.g., list, dict, set).
  • Immutable: Cannot be modified after creation (e.g., int, float, str, tuple).

Example:

        mutable = [1, 2, 3]         mutable[0] = 99         print(mutable) # [99, 2, 3]         immutable = "hello"         immutable[0] = 'H' # Error: 'str' object does not support item assignment

46)How do you open a file in Python? What are the different
modes for opening a file?

The open() function is used to open a file in Python. It takes two arguments:

  • The file name.
  • The mode in which the file is opened.

Common modes are:

  • r: Read (default mode, file must exist).
  • w: Write (creates a new file or overwrites an existing file).
  • a: Append (adds data to the end of the file).
  • rb, wb, ab: Same as above, but for binary files.

Example:

    # Open a file in write mode and write to it     file = open("example.txt", "w")     file.write("Hello, Python!")     file.close()
47)What is the difference between read(), readline(),
and readlines()?
  • read(): Reads the entire file as a string.
  • readline(): Reads one line from the file.
  • readlines(): Reads all lines as a list of strings.

Example:

# Writing content to the file with open("example.txt", "w") as file: file.write("First line\nSecond line\nThird line") # Reading the file with open("example.txt", "r") as file: print(file.read()) # Reads entire file file.seek(0) # Reset cursor to start print(file.readline()) # Reads the first line print(file.readlines()) # Reads all lines as a list
48)What is the difference between w and a modes in file handling?

  • w: Overwrites the file if it exists or creates a new file.
  • a: Appends to the file if it exists or creates a new file.

Example:

# Using 'w' mode

with open("example.txt", "w") as file:

    file.write("This overwrites the file.")

# Using 'a' mode

with open("example.txt", "a") as file:

    file.write("\nThis appends to the file.")

49)What is the difference between import and from ... import?
  • import: Imports the entire module, and you access its contents using the module name.
  • from ... import: Imports specific functions, classes, or variables from a module.

Example:

# Import the entire module

import math

print(math.sqrt(16))  # Output: 4.0

# Import only specific function

from math import sqrt

print(sqrt(16))  # Output: 4.0

50)What is a Python package? How is it different from a module?
  • A module is a single Python file.
  • A package is a collection of modules organized in a directory with an __init__.py file.

Example:
Directory structure for a package named my_package:

my_package/ __init__.py module1.py module2.py

Use the package:
from my_package import module1 module1.some_function()

Comments