Prepare for your Python technical interviews with this comprehensive guide featuring 30 essential questions. Covering basic, intermediate, and advanced topics, these questions help freshers, candidates with 1-3 years experience, and professionals with 3-6 years prepare effectively for roles at companies like Atlassian, Zoho, and Paytm.
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.[1][2]
2. How is Python code executed?
Python source code is first compiled to bytecode through lexical analysis, syntax parsing, semantic analysis, and bytecode generation. The Python Virtual Machine (PVM) then executes this bytecode.[2]
3. What is the difference between a list and a tuple in Python?
Lists are mutable (can be modified after creation) while tuples are immutable. Lists use square brackets [] and tuples use parentheses (). Tuples are faster and consume less memory.[5]
# List (mutable)
my_list = [1, 2, 3]
my_list[0] = 10 # Valid
# Tuple (immutable)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error!
4. What are Python keywords?
Keywords are reserved words that cannot be used as variable names, such as if, else, for, while, def, class, return, lambda, try, except, and import.[6]
5. What is the difference between / and // operators in Python?
The / operator performs true division (returns float), while // performs floor division (returns integer). For example, 7/2 = 3.5 but 7//2 = 3.[1]
print(7/2) # 3.5
print(7//2) # 3
6. How do you check the data type of a variable?
Use the type() function to return the data type of any variable or object.[7]
x = 42
print(type(x)) # <class 'int'>
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.[7]
def my_function():
pass # TODO: Implement later
8. What are global and local variables?
Local variables are defined inside functions and accessible only within that function. Global variables are defined outside functions and accessible throughout the program.[7]
global_var = "I'm global"
def my_function():
local_var = "I'm local"
print(global_var) # Works
# print(local_var) outside function would fail
9. Which collection does not allow duplicate members?
The set data type does not allow duplicate elements and is unordered.[7]
my_set = {1, 2, 2, 3}
print(my_set) # {1, 2, 3}
10. What is PEP 8?
PEP 8 is Python’s style guide for code formatting, covering indentation (4 spaces), line length (79 characters), naming conventions, and whitespace usage.[2]
Intermediate Python Interview Questions (11-20)
11. What are *args and **kwargs in Python functions?
*args allows a function to accept any number of positional arguments as a tuple. **kwargs accepts any number of keyword arguments as a dictionary.[6]
def my_function(*args, **kwargs):
print(args) # (1, 2, 3)
print(kwargs) # {'name': 'John', 'age': 30}
my_function(1, 2, 3, name="John", age=30)
12. Explain list comprehension with an example.
List comprehension provides a concise way to create lists. Syntax: [expression for item in iterable if condition].[1]
# Traditional way
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 a dictionary comprehension?
Dictionary comprehension creates dictionaries concisely using {key_expr: value_expr for item in iterable} syntax.[1]
squares_dict = {i: i**2 for i in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
14. What is the difference between shallow copy and deep copy?
Shallow copy creates a new object but inserts references to original nested objects. Deep copy creates a completely independent copy of all nested objects.[4]
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
15. How do you implement a stack using lists?
Use append() for push, pop() for pop, and [-1] for peek operations.[3]
stack = []
stack.append(1) # push
stack.append(2)
print(stack.pop()) # pop: 2
print(stack[-1]) # peek: 1
16. What is a lambda function?
Lambda functions are anonymous one-liner functions defined using the lambda keyword. They can have any number of arguments but only one expression.[1]
square = lambda x: x**2
print(square(5)) # 25
17. What is the zip() function?
The zip() function combines multiple iterables into tuples of corresponding elements.[4]
names = ['Alice', 'Bob']
ages = [25, 30]
result = list(zip(names, ages))
print(result) # [('Alice', 25), ('Bob', 30)]
18. Explain * unpacking operator.
The * operator unpacks iterables into individual elements. ** unpacks dictionaries into keyword arguments.[6]
numbers = [1, 2, 3]
print(*numbers) # 1 2 3
def func(a, b, c):
print(a, b, c)
func(*[1, 2, 3]) # 1 2 3
19. What is the enumerate() function?
enumerate() adds a counter to an iterable and returns it as enumerate object (index, value) pairs.[1]
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple, 1 banana, 2 cherry
20. How do you read from and write to files?
Use open() with modes ‘r’ (read), ‘w’ (write), ‘a’ (append). Always use with statement for automatic file closing.[1]
with open('file.txt', 'w') as f:
f.write('Hello, Python!')
with open('file.txt', 'r') as f:
content = f.read()
print(content)
Advanced Python Interview Questions (21-30)
21. What is a generator function?
Generator functions use yield instead of return to yield a sequence of values lazily, saving memory for large datasets.[1]
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
22. Explain decorators with an example.
Decorators are functions that modify the behavior of another function. They use @ syntax and wrap functions for added functionality.[1]
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
23. What is the Global Interpreter Lock (GIL)?
GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes simultaneously.[1]
24. Difference between __str__ and __repr__?
__str__ returns a human-readable string representation (called by str() and print()). __repr__ returns official string representation (called by repr()).[1]
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'Point({self.x}, {self.y})'
def __repr__(self):
return f'Point(x={self.x}, y={self.y})'
25. What are class methods and static methods?
Class methods (@classmethod) receive class as first argument (cls). Static methods (@staticmethod) don’t receive self or cls, behave like regular functions.[1]
class MyClass:
@classmethod
def class_method(cls):
print("Class method")
@staticmethod
def static_method():
print("Static method")
26. Explain the difference between iter() and next().
iter() returns an iterator object. next() retrieves the next item from the iterator, raising StopIteration when exhausted.[7]
27. What is a context manager?
Context managers handle resource management using with statement. Implemented via __enter__() and __exit__() methods.[1]
class MyContext:
def __enter__(self):
print("Entering")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting")
28. How does Python memory management work?
Python uses reference counting for memory management. When an object’s reference count reaches zero, it’s deallocated. Garbage collector handles cyclic references.[2]
29. What is the difference between deepcopy and copy in nested lists scenario?
At Atlassian, you might need to copy complex data structures. Shallow copy copies only top-level, nested lists share references. Deep copy creates independent copies.[3][14]
import copy
lst = [[1, 2], [3, 4]]
shallow = copy.copy(lst)
shallow[0][0] = 99
print(lst[0][0]) # 99 (nested list modified!)
deep = copy.deepcopy(lst)
deep[0][0] = 88
print(lst[0][0]) # 99 (original unchanged)
30. Implement a simple LRU Cache in Python.
For Paytm-scale applications, implement LRU Cache using OrderedDict for O(1) get/put operations with capacity limit.[3]
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
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)