Python looks easy, and that is exactly why Python interviews can be tricky. Interviewers know that most freshers can write a loop. What they test is whether you understand how Python actually behaves: why a list changes when you did not expect it, what a generator saves, or why a default argument causes a bug.
Here are the questions asked most often in fresher and junior Python interviews, with short answers and small code examples. Run every example yourself; seeing the output is what makes it stick.
Basics and data types
1. What are the key features of Python?
Readable syntax, dynamically typed, interpreted (executed by an interpreter such as CPython after compiling to bytecode), large standard library, supports procedural, object-oriented and functional styles, and has a huge ecosystem for web, data, automation and AI.
2. List vs tuple vs set vs dictionary?
List: ordered, mutable, allows duplicates. Tuple: ordered, immutable. Set: unordered collection of unique items, fast membership tests. Dictionary: key–value pairs with unique, hashable keys; preserves insertion order (since Python 3.7).
nums = [3, 1, 3] # list
point = (10, 20) # tuple
unique = set(nums) # {1, 3}
ages = {"asha": 24} # dict
3. What is mutable vs immutable?
Mutable objects can change in place (list, dict, set). Immutable objects cannot (int, float, str, tuple, frozenset). "Changing" a string actually creates a new string.
4. What is the difference between == and is?
== compares values; is checks whether two names point to the same object. Use is mainly for None: if x is None.
5. How does slicing work? Reverse a string.
s = "python"
print(s[1:4]) # yth
print(s[::-1]) # nohtyp
Functions
6. What are *args and **kwargs?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.
def log(*args, **kwargs):
print(args, kwargs)
log(1, 2, level="info") # (1, 2) {'level': 'info'}
7. What is the mutable default argument problem?
Default values are created once, when the function is defined, so a mutable default is shared between calls:
def add(item, bucket=[]): # bug
bucket.append(item)
return bucket
add(1); print(add(2)) # [1, 2] (surprise!)
def add_fixed(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
8. What is a lambda? Where do you use map and filter?
nums = [1, 2, 3, 4]
squares = list(map(lambda n: n * n, nums)) # [1, 4, 9, 16]
evens = list(filter(lambda n: n % 2 == 0, nums)) # [2, 4]In practice, list comprehensions are often clearer: [n * n for n in nums].
9. What is a list comprehension?
words = ["api", "sql", "git"]
upper = [w.upper() for w in words if len(w) == 3]
lengths = {w: len(w) for w in words} # dict comprehension
10. What is the scope rule (LEGB)?
Python looks up names in this order: Local, Enclosing function, Global, Built-in. Use global or nonlocal only when you truly need to modify an outer variable.
Iterators, generators and decorators
11. What is a generator and why use it?
A generator produces values one at a time with yield, instead of building the whole list in memory. Ideal for large files or streams.
def read_lines(path):
with open(path) as f:
for line in f:
yield line.strip()
for line in read_lines("big.log"):
if "ERROR" in line:
print(line)
12. Iterator vs iterable?
An iterable can be looped over (list, string, dict); calling iter() on it gives an iterator, which returns items one by one with next() until StopIteration.
13. What is a decorator?
A function that wraps another function to add behaviour without changing its code, such as logging, timing or access checks.
import time
def timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(func.__name__, "took", round(time.perf_counter() - start, 3), "s")
return result
return wrapper
@timed
def build_report():
time.sleep(0.2)
14. What is a context manager (with statement)?
It sets up and reliably cleans up a resource, even if an error occurs. with open("data.csv") as f: closes the file automatically.
Object-oriented Python
15. Explain class, object, __init__ and self.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner # instance attribute
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
self.balance += amount
acc = Account("Ravi")
acc.deposit(500)__init__ initialises a new object; self refers to that object.
16. @staticmethod vs @classmethod vs instance method?
An instance method receives self and works with one object. A @classmethod receives cls and is often used for alternative constructors. A @staticmethod receives neither; it is a utility function grouped inside the class.
17. How does inheritance work? What is MRO?
A child class reuses and can override a parent’s methods; super() calls the parent version. With multiple inheritance, Python follows the Method Resolution Order (MRO), viewable with ClassName.__mro__.
18. What are dunder (magic) methods?
Special methods such as __str__ (readable text), __repr__ (developer representation), __len__, __eq__ and __add__ that let your objects work with built-in operations.
Errors, copying and memory
19. Explain try, except, else and finally.
try:
value = int(user_input)
except ValueError:
print("Please enter a number")
else:
print("Valid:", value) # runs only if no exception
finally:
print("Done") # always runs
20. Shallow copy vs deep copy?
A shallow copy creates a new outer object but shares nested objects; a deep copy copies everything.
import copy
a = [[1, 2], [3]]
b = copy.copy(a) # shallow
c = copy.deepcopy(a) # deep
a[0].append(99)
print(b[0]) # [1, 2, 99] shared
print(c[0]) # [1, 2] independent
21. What is the GIL? Threads vs processes?
In the standard CPython interpreter, the Global Interpreter Lock lets only one thread execute Python bytecode at a time. Threads still help for I/O-bound work (network calls, files); for CPU-heavy work, use multiprocessing. Newer Python versions also offer an optional free-threaded build, but most production code still assumes the GIL.
Practical and ecosystem questions
22. What are modules, packages, pip and virtual environments?
A module is a .py file; a package is a folder of modules. pip installs third-party packages. A virtual environment (python -m venv .venv) keeps each project’s dependencies separate, listed in requirements.txt or pyproject.toml.
23. What is PEP 8?
The official style guide for Python code: naming, indentation (4 spaces), line length and layout. Tools like linters and formatters help follow it.
24. Useful standard library tools?
collections.Counter for counting, defaultdict for grouping, itertools for iteration tricks, datetime, pathlib for files, json and csv.
from collections import Counter
Counter("interview").most_common(2) # [('i', 2), ('e', 2)]
25. For data roles: what is pandas used for?
Loading, cleaning and analysing tabular data with DataFrames: reading CSV or Excel, filtering, grouping, merging and summarising. Expect questions on groupby, merge, handling missing values and loc vs iloc.
Coding questions to practise
- Check whether a string is a palindrome (ignoring case and spaces).
- Count word frequency in a sentence (use Counter or a dict).
- Find the first non-repeating character in a string.
- Remove duplicates from a list while keeping order.
- Find the second largest number without sorting.
- Flatten a nested list; merge two sorted lists.
- Read a CSV file and print the total for each category.
Approach and thinking-aloud tips: coding and logical reasoning questions.
If the role mentions Django or FastAPI
Be ready to explain a request’s journey (URL → view/route → model → database → response), what an ORM does, how you validate input, and how you would build a simple REST endpoint. Our guide on Java vs Python vs .NET explains where Python roles are concentrated.
Frequently Asked Questions
What Python topics are asked in fresher interviews?
Data types and mutability, list vs tuple vs set vs dict, functions with *args and **kwargs, list comprehensions, generators, decorators, OOP basics, exception handling, copying and a few coding problems.
What is the difference between a list and a tuple in Python?
A list is mutable and can change after creation; a tuple is immutable. Tuples are used for fixed data and can be dictionary keys when they contain only hashable items.
What is a generator in Python?
A function that uses yield to produce values one at a time, saving memory compared with building a full list. It is useful for large files and data streams.
What is a decorator in Python?
A function that wraps another function to add behaviour such as logging, timing or access checks without changing the original function’s code.
Is Python enough to get a job?
Python plus SQL, Git and a framework or data library relevant to the role, along with real projects, is what makes freshers employable.
What is the GIL in Python?
The Global Interpreter Lock in CPython allows only one thread to run Python bytecode at a time. Threads still help with I/O-bound tasks; multiprocessing is used for CPU-heavy work.
