Posted in

Top 30 Python Interview Questions and Answers for All Levels

Prepare for your Python interview with these 30 essential questions covering basic, intermediate, and advanced topics. Suitable for freshers, 1-3 years experience, and 3-6 years professionals. Each question includes clear explanations and practical code examples.

Basic Python Interview Questions (1-10)

1. Is Python a compiled language or an interpreted language?

Python is an interpreted language. Python code is executed line-by-line by the Python interpreter without being compiled to machine code beforehand. This makes development faster but slightly slower in execution compared to compiled languages.

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

List is mutable (can be modified after creation), while tuple is immutable (cannot be changed). Lists use square brackets [] and tuples use parentheses ().

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

# Tuple (immutable)  
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # Error!

3. How do you concatenate two lists in Python?

Use the + operator or extend() method. The + operator creates a new list, while extend() modifies the original list.

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

4. What are the benefits of using Python?

Python offers readability, simplicity, extensive libraries, cross-platform compatibility, and rapid development. It’s widely used for web development, data science, automation, and AI at companies like Zoho and Paytm.

5. What is the difference between == and is operators?

== compares values, while is compares object identity (memory location).

a = [1, 2]
b = [1, 2]
print(a == b)  # True (same values)
print(a is b)  # False (different objects)

6. How do you check if a key exists in a dictionary?

Use in keyword, get() method, or keys() method.

my_dict = {'name': 'John', 'age': 30}
print('name' in my_dict)      # True
print(my_dict.get('name'))    # John (None if key missing)

7. What is slicing in Python?

Slicing extracts portions of sequences (lists, strings, tuples) using sequence[start:stop:step].

my_list = [0, 1, 2, 3, 4, 5]
print(my_list[1:4])    # [1, 2, 3]
print(my_list[::2])    # [0, 2, 4] (every second element)
print(my_list[::-1])   # [5, 4, 3, 2, 1, 0] (reverse)

8. What does len() function do?

len() returns the number of items in an object (list, string, dictionary, etc.).

print(len([1, 2, 3]))     # 3
print(len("Python"))       # 6
print(len({'a': 1}))       # 1

9. Which collection does not allow duplicate members?

Set does not allow duplicate elements and is unordered.

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

10. What is the pass statement used for?

pass is a null operation; nothing happens when executed. Used as placeholder when statement is required syntactically.

def my_function():
    pass  # TODO: implement later

Intermediate Python Interview Questions (11-20)

11. What is the difference between global and local scope?

Local scope variables exist only within a function. Global scope variables are accessible throughout the program. Use global keyword to modify global variables inside functions.

12. Explain list comprehension with an example.

List comprehension provides a concise way to create lists.

# Traditional way
squares = []
for i in range(5):
    squares.append(i**2)

# List comprehension
squares = [i**2 for i in range(5)]  # [0, 1, 4, 9, 16]

13. What are lambda functions?

Lambda functions are anonymous, single-expression functions defined using lambda keyword. Useful for short, one-time functions.

square = lambda x: x**2
print(square(5))  # 25

# With filter
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))  # [2, 4]

14. What is the difference between deepcopy and shallow copy?

Shallow copy copies only the top-level object (nested objects share references). Deep copy creates independent copy of all objects recursively.

import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

15. How does Python handle memory management?

Python uses automatic garbage collection with reference counting. When an object’s reference count reaches zero, it’s deallocated. gc module handles cyclic references.

16. What are generators in Python?

Generators are functions that yield values one at a time using yield, saving memory for large datasets.

def count_up_to(n):
    for i in range(n):
        yield i

counter = count_up_to(3)
print(list(counter))  # [0, 1, 2]

17. What is a decorator in Python?

Decorators are functions that modify the behavior of another function. They wrap functions to add functionality.

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

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

say_hello()

18. Explain *args and **kwargs.

*args collects extra positional arguments as tuple. **kwargs collects extra keyword arguments as dictionary.

def func(*args, **kwargs):
    print(args)    # (1, 2, 3)
    print(kwargs)  # {'a': 4, 'b': 5}

func(1, 2, 3, a=4, b=5)

19. What is the Global Interpreter Lock (GIL)?

GIL is a mutex that prevents multiple native threads from executing Python bytecodes simultaneously in CPython. It simplifies memory management but limits true multi-threading.

20. How do you implement a stack using lists?

Use append() for push, pop() for pop, and [-1] for peek.

stack = []
stack.append(1)  # push
stack.append(2)
print(stack.pop())    # 2 (pop)
print(stack[-1])      # 1 (peek)

Advanced Python Interview Questions (21-30)

21. What are metaclasses in Python?

Metaclasses are classes of classes. They define how classes behave. Use type or custom metaclass for class creation customization.

22. Explain __init__, __new__, and __str__ methods.

__new__ creates instance, __init__ initializes it, __str__ defines string representation.

class Person:
    def __new__(cls):
        print("Creating object")
        return super().__new__(cls)
    
    def __init__(self):
        print("Initializing")
    
    def __str__(self):
        return "Person object"

p = Person()

23. What is monkey patching?

Monkey patching dynamically modifies classes or modules at runtime. Useful for debugging or extending third-party code.

class MyClass:
    def method(self):
        return "Original"

# Monkey patch
MyClass.method = lambda self: "Patched"
obj = MyClass()
print(obj.method())  # Patched

24. How do you create a singleton class?

Singleton ensures only one instance exists. Use metaclass or module-level variable.

class Singleton:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

25. What is the difference between classmethod and staticmethod?

@classmethod receives class as first argument (cls). @staticmethod doesn’t receive class or instance.

class MyClass:
    @classmethod
    def class_method(cls):
        return f"Class: {cls.__name__}"
    
    @staticmethod
    def static_method():
        return "Static method"

26. Explain context managers and the with statement.

Context managers handle resource management (files, locks). Use with statement for automatic cleanup.

with open('file.txt', 'r') as f:
    data = f.read()
# File automatically closed

27. What are async and await keywords?

async defines asynchronous functions (coroutines). await pauses execution until coroutine completes, enabling non-blocking I/O.

import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return "Data"

data = asyncio.run(fetch_data())

28. How do you implement a LRU Cache in Python?

Use OrderedDict with move_to_end() for LRU behavior.

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cache = OrderedDict()
        self.capacity = capacity
    
    def get(self, key):
        if key in self.cache:
            self.cache.move_to_end(key)
            return self.cache[key]
        return -1

29. What is the difference between itertools.product and nested loops?

itertools.product generates Cartesian product efficiently, replacing nested loops.

import itertools
print(list(itertools.product([1,2], ['a','b'])))
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

30. How do you test asynchronous code using unittest?

Use asyncio event loop in test methods for async functions at companies like Salesforce and Atlassian.

import unittest
import asyncio

class TestAsync(unittest.TestCase):
    def test_async_function(self):
        loop = asyncio.get_event_loop()
        result = loop.run_until_complete(fetch_data())
        self.assertEqual(result, "expected_data")

## Key Citations
[1] GeeksforGeeks Python Interview Questions
[2] CodeSignal Python Interview Questions
[3] YouTube 50 Most Asked Python Questions
[5] W3Schools Python Interview Questions
[6] InterviewBit Python Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *