Posted in

Top 30 Python Interview Questions and Answers for All Levels

Prepare for Your Python Interview with These Essential Questions

This comprehensive guide features 30 Python interview questions covering basic, intermediate, and advanced topics. Whether you’re a fresher, have 1-3 years of experience, or are a seasoned professional with 3-6 years, these questions will help you demonstrate your Python expertise to companies like Zoho, Atlassian, and Swiggy.

Basic Python Interview Questions (1-10)

1. What are the key features of Python?

Python is an interpreted, high-level programming language known for its readability, dynamic typing, and extensive standard library. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.

2. How is Python executed?

Python source code is compiled to bytecode and then executed by the Python Virtual Machine (PVM). The process involves lexical analysis, syntax parsing, semantic analysis, and bytecode generation before execution.

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

Lists are mutable (can be modified after creation) and defined with square brackets []. Tuples are immutable (cannot be changed) and defined with parentheses (). Tuples are faster and use less memory.

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

# Tuple (immutable)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # This would raise an error

4. What are Python keywords?

Keywords are reserved words that cannot be used as variable names. Examples include if, else, for, while, def, class, return, and lambda.

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

== compares the values of two objects, while is compares object identities (memory location). For small integers and some strings, they may behave similarly due to interning.

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

6. What does len() do?

The len() function returns the number of items in an object. It works with sequences (lists, tuples, strings) and collections (dictionaries, sets).

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

7. What is the pass statement used for?

The pass statement is a null operation; it does nothing when executed. It’s used as a placeholder when a statement is required syntactically but no action is needed.

def my_function():
    pass  # TODO: Implement later

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

Use the in keyword or the get() method with a default value. The in operator is preferred for simple existence checks.

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

9. What is type casting in Python?

Type casting converts one data type to another using functions like int(), str(), float(), list(), and tuple().

num_str = "123"
num_int = int(num_str)
print(num_int + 10)  # 133

10. What is PEP 8?

PEP 8 is Python’s style guide for code formatting. It defines conventions for line length (79 characters), indentation (4 spaces), naming (snake_case), and spacing to improve code readability.

Intermediate Python Interview Questions (11-20)

11. What are *args and **kwargs?

*args allows a function to accept any number of positional arguments as a tuple. **kwargs accepts any number of keyword arguments as a dictionary.

def flexible_function(*args, **kwargs):
    print("Positional:", args)
    print("Keyword:", kwargs)

flexible_function(1, 2, 3, name="Alice", age=25)
# Positional: (1, 2, 3)
# Keyword: {'name': 'Alice', 'age': 25}

12. Explain list comprehension with an example.

List comprehension provides a concise way to create lists. Syntax: [expression for item in iterable if condition].

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

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

13. What is the difference between shallow copy and deep copy?

Shallow copy (copy.copy()) creates a new object but inserts references to nested objects. Deep copy (copy.deepcopy()) creates independent copies of all nested objects.

14. What are lambda functions?

Lambda functions are anonymous, single-expression functions defined using the lambda keyword. They’re often used for short, one-time operations.

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))
print(evens)  # [2, 4]

15. What is a dictionary comprehension?

Dictionary comprehension creates dictionaries concisely. Syntax: {key_expr: value_expr for item in iterable if condition}.

squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

16. Explain global vs local scope.

Local variables exist only within a function. Global variables are defined outside functions and accessible everywhere. Use global keyword to modify global variables inside functions.

x = 10  # Global
def my_func():
    x = 20  # Local
    print(x)  # 20

my_func()
print(x)  # 10

17. What is the zip() function?

The zip() function pairs elements from multiple iterables into tuples. It stops at the shortest iterable.

names = ['Alice', 'Bob']
ages = [25, 30]
paired = list(zip(names, ages))
print(paired)  # [('Alice', 25), ('Bob', 30)]

18. How do you read from and write to files?

Use open() with modes like 'r' (read), 'w' (write), 'a' (append). Always use with statement for automatic file closing.

# Write
with open('file.txt', 'w') as f:
    f.write('Hello, Python!')

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

19. What are sets in Python?

Sets are unordered collections of unique elements. They are mutable but contain only immutable elements. Useful for membership testing and eliminating duplicates.

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

print(2 in my_set)  # True

20. What is the purpose of __init__() method?

__init__() is a constructor method called when an object is created. It initializes instance variables.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('Alice', 25)
print(p.name)  # Alice

Advanced Python Interview Questions (21-30)

21. What are decorators?

Decorators are functions that modify the behavior of another function or class. They use @decorator syntax and are useful for logging, authentication, and memoization.

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

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

say_hello()

22. Explain generators and the yield keyword.

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

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

for num in count_up_to(3):
    print(num)  # 1, 2, 3

23. What is a closure?

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

def outer(x):
    def inner(y):
        return x + y
    return inner

add_five = outer(5)
print(add_five(3))  # 8

24. What are class methods and static methods?

Class methods (@classmethod) operate on the class itself using cls. Static methods (@staticmethod) don't access instance or class data.

class MyClass:
    @classmethod
    def class_method(cls):
        print("Class method")
    
    @staticmethod
    def static_method():
        print("Static method")

25. Scenario: At Paytm, how would you handle memory-efficient processing of 1 million records?

Use generators or iterate through data in chunks instead of loading everything into memory. Process records one at a time with yield.

def process_large_file(file_path):
    with open(file_path, 'r') as f:
        for line in f:  # Memory efficient
            # Process each line
            yield line.strip()

26. 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 multithreading.

27. Scenario: Implement a stack using Python lists for Salesforce backend processing.

A stack follows LIFO principle with push, pop, and peek operations using list methods append and pop.

class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        return self.items.pop()
    
    def peek(self):
        return self.items[-1]

28. What are metaclasses?

Metaclasses are classes of classes. They define class behavior. The default metaclass is type. Use when you need to modify class creation.

29. Scenario: At Adobe, optimize this nested loop for image processing (O(n²) to O(n)).

Convert nested loops to use dictionaries or sets for O(1) lookups instead of O(n) searches.

# Before: O(n²)
for i in data:
    for j in data:
        if i == j:
            # process

# After: O(n) using set
data_set = set(data)
for i in data:
    if i in data_set:
        # process

30. Explain Python's memory management.

Python uses reference counting and cyclic garbage collection. Reference counting tracks object references; garbage collector handles circular references using generational collection.

Master these 30 Python interview questions to confidently tackle technical interviews across all experience levels. Practice coding each example to solidify your understanding!

Leave a Reply

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