Python interviews for freshers test whether you understand the core language: data types, mutability, functions, object-oriented programming, error handling and a few short coding problems. Here are 30 questions that come up most often, each with a short answer and code you can run yourself.
Type every example into a Python shell before your interview. If you are still learning, start with our 60-day Python plan for beginners.
Python basics
1. What are the key features of Python?
Python is interpreted, dynamically typed, readable, and has a large standard library and package ecosystem. It supports procedural, object-oriented and functional styles.
2. What is the difference between a list and a tuple?
| List | Tuple |
|---|---|
| Mutable: can be changed | Immutable: cannot be changed |
Square brackets [1, 2] |
Round brackets (1, 2) |
| Slightly slower, more methods | Faster, can be a dictionary key |
3. Which data types are mutable?
Mutable: list, dict, set, bytearray. Immutable: int, float, str, tuple, frozenset, bool. Mutability matters when you pass objects to functions or use them as dictionary keys.
4. What is the difference between is and ==?
== compares values. is checks whether two names point to the same object in memory. Use is only for None, as in if x is None.
5. How is memory managed in Python?
CPython uses reference counting: an object is freed when nothing refers to it. A garbage collector also finds groups of objects that refer to each other but are no longer used.
6. What are *args and **kwargs?
def show(*args, **kwargs):
print(args) # tuple of positional arguments
print(kwargs) # dict of keyword arguments
show(1, 2, city='Pune')
# (1, 2)
# {'city': 'Pune'}
7. What is the mutable default argument problem?
def add(item, items=[]): # bug: the same list is reused
items.append(item)
return items
def add(item, items=None): # fix
if items is None:
items = []
items.append(item)
return items
Strings, lists and dictionaries
8. What is a list comprehension?
squares = [n * n for n in range(10) if n % 2 == 0]
# [0, 4, 16, 36, 64]
9. How do you reverse a string?
name = 'radium'
print(name[::-1]) # muidar
10. Shallow copy vs deep copy?
A shallow copy creates a new outer object but shares the inner objects. A deep copy copies everything recursively.
import copy
a = [[1, 2], [3, 4]]
b = copy.copy(a)
c = copy.deepcopy(a)
a[0].append(99)
print(b[0]) # [1, 2, 99] shared
print(c[0]) # [1, 2] independent
11. How do you merge two dictionaries?
a = {'x': 1}
b = {'y': 2}
merged = a | b # Python 3.9+
merged = {**a, **b} # older versions
12. How do you count items in a list?
from collections import Counter
Counter(['a', 'b', 'a', 'c', 'a']).most_common(1)
# [('a', 3)]
13. What is the difference between append and extend?
append adds one item, even if it is a list. extend adds each item of an iterable. [1].append([2, 3]) gives [1, [2, 3]]; extend gives [1, 2, 3].
Functions and advanced concepts
14. What is a lambda function?
A small anonymous function written in one expression, often used as a sort key.
people = [('Asha', 31), ('Ravi', 24)]
people.sort(key=lambda p: p[1])
15. What is a decorator?
A function that takes another function and returns a new one with extra behaviour, such as logging or timing, without changing the original code.
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(func.__name__, round(time.perf_counter() - start, 3), 's')
return result
return wrapper
@timer
def slow():
time.sleep(1)
16. What is a generator?
A function that uses yield to produce values one at a time instead of building a full list. It saves memory for large data such as reading a big log file line by line.
def evens(limit):
for n in range(0, limit, 2):
yield n
17. Iterator vs iterable?
An iterable is anything you can loop over (list, string, file). An iterator is the object that produces the next value with next(). Calling iter() on an iterable gives an iterator.
18. What is the GIL?
The Global Interpreter Lock lets only one thread execute Python bytecode at a time in CPython. Threads still help for I/O-bound work such as network calls; for CPU-bound work use multiprocessing or libraries written in C such as NumPy.
Object-oriented programming
19. What is __init__ and self?
__init__ runs when a new object is created and sets its starting state. self refers to the current object, so methods can read and change its attributes.
20. Explain inheritance with an example.
class Employee:
def __init__(self, name):
self.name = name
def role(self):
return 'employee'
class Developer(Employee):
def role(self):
return 'developer'
print(Developer('Asha').role()) # developer
21. What are class methods and static methods?
A @classmethod receives the class as cls and is often used for alternative constructors. A @staticmethod receives neither the object nor the class; it is a helper that lives inside the class for organisation.
22. What are dunder methods?
Special methods with double underscores, such as __str__, __len__ and __eq__, that let your objects work with built-in functions and operators.
Errors and files
23. How does exception handling work?
try:
value = int(input('Age: '))
except ValueError:
print('Please enter a number')
else:
print('Saved')
finally:
print('Done')
24. Why use with when opening files?
The with statement closes the file automatically, even if an error occurs.
with open('data.txt') as f:
for line in f:
print(line.strip())
Common coding questions
25. Check if a string is a palindrome.
def is_palindrome(s):
s = ''.join(ch.lower() for ch in s if ch.isalnum())
return s == s[::-1]
26. Find duplicates in a list.
def duplicates(items):
seen, dupes = set(), set()
for x in items:
if x in seen:
dupes.add(x)
seen.add(x)
return dupes
27. FizzBuzz.
for n in range(1, 16):
out = ('Fizz' if n % 3 == 0 else '') + ('Buzz' if n % 5 == 0 else '')
print(out or n)
28. Find the second largest number.
def second_largest(nums):
unique = sorted(set(nums))
return unique[-2] if len(unique) > 1 else None
29. Count word frequency in a sentence.
from collections import Counter
Counter('the cat and the hat'.split())
30. Two-sum: return indexes of two numbers that add to a target.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target - n], i
seen[n] = i
Explain that this runs in O(n) time because dictionary lookups are constant time on average. Interviewers care about that reasoning as much as the code.
Frequently asked questions
Are Python interviews hard for freshers?
Not if you practise. Most fresher rounds check core concepts and easy coding problems. Solve two problems a day for a month and explain your solutions aloud.
Which Python topics are asked most?
Lists vs tuples, dictionaries, mutability, comprehensions, decorators, generators, OOP and exception handling, plus string and list coding problems.
Do I need to know Django or pandas?
Only for the role. Web developer interviews add Django or Flask; data roles add pandas and SQL; testing roles add pytest and Selenium.
Keep practising with our Python tutorials, or prepare for data roles with data science interview questions.