Interview Prep
Interview Questions on Python for Freshers — Data Types, OOPs, Libraries, and What Companies Actually Ask
Python has overtaken Java as the most popular language for freshers in India. TCS, Infosys, Wipro, and every data-focused company now test Python in their technical rounds. Here are the exact questions they ask — with code examples and the depth they expect.

Python is now the default language for data roles, automation, and scripting interviews in India. Every fresher should know it.
Python for Freshers — What Interviewers Test
Python has become the go-to language for freshers in India. It is the primary language for data analyst, data scientist, automation, and backend roles. Even service companies like TCS and Infosys now include Python in their campus placement rounds alongside Java.
Fresher Python interviews follow a predictable pattern: data types and mutability, list/dict/set operations, string manipulation, OOPs concepts, file handling, and basic library questions (NumPy, Pandas for data roles). If you know these topics well, you can clear most fresher-level Python interviews.
This guide covers the actual Python questions asked to freshers in Indian interviews — organized by topic, with code examples and the output interviewers expect you to predict.
Python interviews for freshers are 60% core language concepts and 40% practical coding. Interviewers want to see that you can write clean Python, not just memorize syntax.
Data Types and Mutability
Understanding Python's data types and the difference between mutable and immutable objects is the foundation of every Python interview.
Q1: What are mutable and immutable data types in Python?
# Immutable — cannot be changed after creation
# int, float, str, tuple, frozenset, bool
x = "hello"
x[0] = "H" # TypeError! Strings are immutable
x = "Hello" # This creates a NEW string, not modifying old one
# Mutable — can be changed in place
# list, dict, set, bytearray
my_list = [1, 2, 3]
my_list[0] = 10 # Works! Lists are mutable
print(my_list) # [10, 2, 3]
# Why it matters:
# 1. Immutable objects are hashable (can be dict keys)
# 2. Mutable default arguments are a common bug:
def add_item(item, lst=[]): # BAD! Shared default list
lst.append(item)
return lst
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] — NOT [2]!
# Fix:
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lstQ2: What is the difference between list, tuple, set, and dictionary?
# List — ordered, mutable, allows duplicates
fruits = ["apple", "banana", "apple"]
fruits.append("cherry")
# Tuple — ordered, immutable, allows duplicates
coords = (10, 20, 30)
# coords[0] = 5 # TypeError!
# Set — unordered, mutable, NO duplicates
unique = {1, 2, 3, 2, 1}
print(unique) # {1, 2, 3}
# Dictionary — key-value pairs, ordered (3.7+), mutable
student = {"name": "Rahul", "age": 22, "city": "Bangalore"}
student["grade"] = "A" # add new key
# When to use which:
# List → ordered collection, need index access
# Tuple → fixed data (coordinates, RGB), dict keys
# Set → remove duplicates, membership testing (fast)
# Dict → key-value mapping, lookups by keyQ3: What is the difference between == and ‘is’ in Python?
# == checks VALUE equality # is checks IDENTITY (same object in memory) a = [1, 2, 3] b = [1, 2, 3] c = a a == b # True (same values) a is b # False (different objects) a is c # True (same object) # Integer caching (Python caches -5 to 256): x = 256 y = 256 x is y # True (cached) x = 257 y = 257 x is y # False (not cached — new objects) # Rule: always use == for comparison # Use 'is' only for None checks: if x is None
Strings and List Operations
Q4: Reverse a string. Find if a string is a palindrome.
# Reverse a string:
s = "hello"
reversed_s = s[::-1] # "olleh" (slicing)
# Other methods:
reversed_s = "".join(reversed(s))
# Check palindrome:
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("madam")) # True
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
# String slicing is the most Pythonic approach.
# Interviewers expect you to know s[::-1]Q5: List comprehension — what is it and when to use it?
# List comprehension = concise way to create lists
# Traditional loop:
squares = []
for i in range(10):
squares.append(i ** 2)
# List comprehension (same result):
squares = [i ** 2 for i in range(10)]
# With condition:
evens = [i for i in range(20) if i % 2 == 0]
# Nested:
matrix = [[1,2,3], [4,5,6], [7,8,9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Dict comprehension:
word_lengths = {word: len(word) for word in ["hello", "world"]}
# {"hello": 5, "world": 5}
# Set comprehension:
unique_lengths = {len(word) for word in ["hi", "hello", "hey"]}
# {2, 5, 3}
# When NOT to use:
# Complex logic — use a regular loop for readability
# Side effects — comprehensions are for creating dataQ6: What is the difference between append(), extend(), and insert()?
lst = [1, 2, 3] # append() — adds ONE element to the end lst.append(4) # [1, 2, 3, 4] lst.append([5, 6]) # [1, 2, 3, 4, [5, 6]] — nested! # extend() — adds EACH element from iterable lst = [1, 2, 3] lst.extend([4, 5]) # [1, 2, 3, 4, 5] — flat # insert() — adds element at specific index lst = [1, 2, 3] lst.insert(1, "a") # [1, "a", 2, 3] # Common mistake: # Using append when you mean extend # append([4,5]) gives nested list # extend([4,5]) gives flat list
Functions and Scope
Q7: What are *args and **kwargs?
# *args — variable number of positional arguments (tuple)
def add(*args):
return sum(args)
add(1, 2, 3) # 6
add(1, 2, 3, 4, 5) # 15
# **kwargs — variable number of keyword arguments (dict)
def greet(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
greet(name="Priya", age=22, city="Mumbai")
# name: Priya
# age: 22
# city: Mumbai
# Both together:
def func(a, b, *args, **kwargs):
print(a, b) # positional
print(args) # extra positional as tuple
print(kwargs) # extra keyword as dict
func(1, 2, 3, 4, x=5, y=6)
# 1 2
# (3, 4)
# {'x': 5, 'y': 6}Q8: What is a lambda function? When to use it?
# Lambda = anonymous, single-expression function
# Regular function:
def square(x):
return x ** 2
# Lambda equivalent:
square = lambda x: x ** 2
# Common use cases:
# 1. Sorting with custom key
students = [("Rahul", 85), ("Priya", 92), ("Amit", 78)]
students.sort(key=lambda x: x[1]) # sort by marks
# 2. With map/filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x%2 == 0, numbers))
# 3. With sorted
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=lambda w: len(w))
# When NOT to use lambda:
# Multi-line logic — use a regular function
# Complex conditions — readability matters
# Reusable logic — name it with defQ9: What are decorators in Python?
# Decorator = function that modifies another function
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.2f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
return "done"
slow_function() # prints: slow_function took 1.00s
# Common built-in decorators:
# @staticmethod — no self parameter
# @classmethod — cls parameter instead of self
# @property — access method like an attribute
# Decorators are syntactic sugar for:
# slow_function = timer(slow_function)
Python's simplicity is deceptive. Interviewers test whether you understand what happens under the hood — mutability, scope, and memory management.
OOPs in Python
Q10: Explain OOPs concepts in Python with examples.
# Encapsulation — bundling data + methods
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private (name mangling)
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
# Inheritance
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Polymorphism — same interface, different behavior
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # Woof! then Meow!
# Abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# Multiple inheritance (Python supports it):
class A:
pass
class B:
pass
class C(A, B): # inherits from both A and B
passQ11: What is the difference between __init__ and __new__?
__new__ creates the instance (allocates memory). __init__ initializes the instance (sets attributes). __new__ is called first, returns the instance, then __init__ is called on that instance. In practice, you almost always override __init__ only. __new__ is used for advanced patterns like singletons or immutable types.
Q12: What is self in Python?
self refers to the current instance of the class. It is the first parameter of every instance method. When you call obj.method(), Python automatically passes obj as self. It is not a keyword — you could name it anything, but self is the universal convention. Unlike Java's this, Python requires you to explicitly include self in the method signature.
Exception Handling and File Operations
Q13: How does exception handling work in Python?
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type/Value error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No error occurred") # runs if NO exception
finally:
print("Always runs") # cleanup code
# Custom exception:
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.message = f"Cannot withdraw {amount}. Balance: {balance}"
super().__init__(self.message)
# Raise custom exception:
raise InsufficientFundsError(100, 500)
# Key difference from Java:
# Python uses try/except (not try/catch)
# Python has else block (runs if no exception)Q14: What is the ‘with’ statement? Why use it for file handling?
# Without 'with' — must manually close file:
f = open("data.txt", "r")
content = f.read()
f.close() # easy to forget!
# With 'with' — auto-closes file:
with open("data.txt", "r") as f:
content = f.read()
# file is automatically closed here
# 'with' uses context managers (__enter__ and __exit__)
# It guarantees cleanup even if an exception occurs
# File modes:
# "r" — read (default)
# "w" — write (overwrites)
# "a" — append
# "r+" — read + write
# "rb" — read binary (images, PDFs)Preparation Plan for Freshers
Week 1: Data Types + Strings + Lists
Master mutable vs immutable, list comprehensions, string slicing, and dictionary operations. Write code for each — do not just read.
Week 2: Functions + OOPs
*args/**kwargs, lambda, decorators, and all four OOPs pillars with Python code. Practice writing classes with inheritance and polymorphism.
Week 3: Exception Handling + File I/O + Libraries
try/except patterns, context managers, and basic NumPy/Pandas if applying for data roles. Practice reading CSV files and basic data manipulation.
Week 4: Coding Problems + Mock Interviews
Solve 3-5 Python coding problems daily: reverse string, find duplicates, sort dictionary by value, flatten nested list. Practice explaining your code out loud.
Company-Wise Python Question Focus
TCS / Infosys
- • Data types & mutability
- • String operations
- • List/dict methods
- • Basic OOPs
- • Simple coding
Data Roles
- • NumPy arrays
- • Pandas DataFrames
- • List comprehensions
- • File handling (CSV)
- • Lambda + map/filter
Product Companies
- • Decorators
- • Generators & iterators
- • Context managers
- • Memory management
- • DSA in Python