Prepare for Your Python Interview with These Essential Questions
Whether you’re a fresher, have 1-3 years of experience, or are a seasoned developer with 3-6 years in Python, this comprehensive guide covers 30 essential Python interview questions arranged by difficulty level. From basic concepts to advanced scenarios, master Python fundamentals that top companies like Amazon, Zoho, and Atlassian expect from candidates.
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 first. The interpreter converts Python code to bytecode, which is then executed by the Python Virtual Machine (PVM).[1][2]
2. How do you concatenate two lists in Python?
You can concatenate two lists using the + operator or the extend() method:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Using + operator
result1 = list1 + list2
print(result1) # [1, 2, 3, 4, 5, 6]
# Using extend() method
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
3. What is the difference between a list and a tuple in Python?
Lists are mutable (can be modified), while tuples are immutable (cannot be modified after creation). Lists use square brackets [], tuples use parentheses ().[3][4]
4. What are the four main data types in Python?
The four main built-in data types in Python are:
- List – Ordered, mutable collection:
[1, 2, 3] - Tuple – Ordered, immutable collection:
(1, 2, 3) - Set – Unordered, mutable, no duplicates:
{1, 2, 3} - Dictionary – Unordered, mutable key-value pairs:
{"key": "value"}
5. What is the difference between == and is operators?
== compares values, while is compares object identity (memory location):
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (same values)
print(a is b) # False (different objects)
6. What does the len() function do?
The len() function returns the number of items in an object:
my_list = [1, 2, 3, 4]
print(len(my_list)) # 4
my_string = "Hello"
print(len(my_string)) # 5
7. How do you check if a key exists in a dictionary?
Use the in keyword or the get() method:
my_dict = {"name": "John", "age": 30}
print("name" in my_dict) # True
print(my_dict.get("name")) # John
print(my_dict.get("city")) # None (no KeyError)
8. What is slicing in Python?
Slicing extracts a portion of a sequence using sequence[start:stop:step]:
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[1:4]) # [1, 2, 3]
print(my_list[:3]) # [0, 1, 2]
print(my_list[::2]) # [0, 2, 4] (every second element)
9. What is the pass statement used for?
The pass statement is a null operation (no-op) used as a placeholder when a statement is required syntactically but no action is needed:
def my_function():
pass # TODO: Implement later
10. How do you reverse a string in Python?
Use slicing with step -1:
text = "Hello"
reversed_text = text[::-1]
print(reversed_text) # "olleH"
Intermediate Python Interview Questions (11-20)
11. What is the difference between / and // in Python?
/ performs true division (always returns float), // performs floor division (returns integer):
print(7 / 2) # 3.5
print(7 // 2) # 3
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)]
print(squares) # [0, 1, 4, 9, 16]
13. What are lambda functions?
Lambda functions are anonymous, single-expression functions:
# Lambda function
square = lambda x: x**2
print(square(5)) # 25
# Using with sorted()
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
14. What is the Global Interpreter Lock (GIL)?
The GIL is a mutex that prevents multiple native threads from executing Python bytecodes simultaneously in CPython. This limits true multi-threading for CPU-bound tasks.[1]
15. Difference between shallow copy and deep copy?
Shallow copy copies references (nested objects remain shared), deep copy creates independent copies of all objects:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 99
print(original[0][0]) # 99 (shallow affects nested)
print(deep[0][0]) # 1 (deep is independent)
16. What are generators in Python?
Generators are functions that yield values one at a time, saving memory for large sequences:
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
17. What is the zip() function?
zip() combines multiple iterables into tuples:
names = ['Alice', 'Bob']
ages = [25, 30]
result = list(zip(names, ages))
print(result) # [('Alice', 25), ('Bob', 30)]
18. Explain *args and **kwargs.
*args collects extra positional arguments as a tuple, **kwargs collects extra keyword arguments as a 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 a decorator?
A decorator wraps a function to extend its behavior without modifying the original function:
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()
20. How do you read a file in Python?
Use open() with context manager:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
Advanced Python Interview Questions (21-30)
21. What is the difference between __str__ and __repr__?
__str__ returns a human-readable string (for print()), __repr__ returns a developer-friendly string representation:
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
22. Implement a stack using a list.
A stack follows LIFO (Last In, First Out):
stack = []
def push(item):
stack.append(item)
def pop():
if stack:
return stack.pop()
return None
def peek():
if stack:
return stack[-1]
return None
push(1)
push(2)
print(pop()) # 2
print(peek()) # 1
23. What are class methods and static methods?
Class methods operate on the class (@classmethod), static methods don’t access instance/class (@staticmethod):
class MyClass:
class_var = "I am class variable"
@classmethod
def class_method(cls):
return cls.class_var
@staticmethod
def static_method():
return "I am static"
24. Explain memory management in Python.
Python uses reference counting and garbage collection. Reference counting tracks object references; when count reaches zero, memory is freed. Garbage collector handles cyclic references.[1]
25. What is metaclass in Python?
A metaclass defines how a class behaves. Classes are instances of metaclasses. The default metaclass is type:
class MetaClass(type):
def __new__(cls, name, bases, attrs):
attrs['custom_attr'] = 'Added by metaclass'
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=MetaClass):
pass
print(MyClass.custom_attr) # Added by metaclass
26. How does Python handle exceptions?
Use try-except-finally blocks:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Cleanup code")
27. What are context managers?
Context managers handle resource management using with statement:
class FileManager:
def __enter__(self):
print("Opening file")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing file")
with FileManager():
print("Working with file")
28. Scenario: At Paytm, how would you find duplicates in a list efficiently?
Use a set for O(n) time complexity:
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
print(find_duplicates([1, 2, 2, 3, 1, 4])) # [1, 2]
29. Scenario: At Salesforce, implement a function to check if two words are anagrams.
Compare sorted versions or character counts:
def are_anagrams(word1, word2):
return sorted(word1.lower()) == sorted(word2.lower())
print(are_anagrams("listen", "silent")) # True
30. What is the difference between iter() and next()?
iter() creates an iterator from an iterable, next() retrieves the next value:
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2