Python Interview Questions for Freshers (2026): 60+ Questions with Answers, Coding Problems and Output Puzzles

What Python questions are asked to freshers? Almost every fresher interview covers the same core: data types (list, tuple, set, dictionary), mutable vs immutable, functions (*args, **kwargs, lambda), OOP, exception handling, file handling, list comprehensions, and a few coding problems such as reversing a string, finding duplicates or checking a palindrome. For data roles, expect basic Pandas and NumPy questions too.

This guide from VibrantMinds Technologies in Pune covers 60+ Python interview questions for freshers with short answers and runnable code, plus output-prediction puzzles, 15 coding problems with solutions, a revision cheat sheet and a 14-day preparation plan. If you’ve been searching for Python interview questions for freshers, Python interview questions and answers, Python coding interview questions for freshers, Python OOP interview questions, Pandas and NumPy interview questions for freshers, Python developer fresher jobs in Pune or free IT job WhatsApp groups for freshers in Pune, this is built to be the complete answer.

Code in this guide is written for Python 3. Behaviour of some features differs between versions, so check your own version with python --version.

HOW THE PYTHON INTERVIEW USUALLY FLOWS




For Python developer roles, expect more on OOP, functions and frameworks (such as Django or Flask). For Python and Data Science roles, expect Pandas, NumPy, data cleaning and basic statistics along with core Python.

WHAT THE TOP SEARCH RESULTS COVER, AND WHAT THIS GUIDE ADDS

Pages ranking for these searches mostly list 50 to 130 questions with short definitions. This guide keeps the coverage and adds:

  • Output-prediction puzzles with explanations, which many tests use

  • 15 coding problems with solutions and complexity notes

  • A traps column (common mistakes interviewers notice)

  • A data science section (Pandas and NumPy) for Python + Data Science freshers

  • A one-page cheat sheet and a 14-day plan

  • Advice on how to answer and what to say about projects

ONE-PAGE PYTHON CHEAT SHEET (REVISE THIS FIRST)

Structure

Syntax

Ordered?

Mutable?

Duplicates?

Typical use

list

[1, 2, 3]

Yes

Yes

Yes

General collections

tuple

(1, 2, 3)

Yes

No

Yes

Fixed data, dictionary keys

set

{1, 2, 3}

No (no index)

Yes

No

Unique items, fast membership

dict

{"a": 1}

Yes (insertion order, Python 3.7+)

Yes

Keys unique

Key-value lookup

str

"hello"

Yes

No

Yes

Text




MODULE 1: PYTHON BASICS (Q1 TO Q12)

Q1. What is Python and why is it popular?
Python is a high-level, general-purpose programming language known for readable syntax. It’s widely used in web development, automation, data science, machine learning and scripting, and it has a large library ecosystem.

Q2. Is Python compiled or interpreted?
In the standard implementation (CPython), source code is first compiled to bytecode and then executed by the Python virtual machine. It’s commonly described as interpreted.

Q3. What does “dynamically typed” mean?
You don’t declare a variable’s type. The type is determined at runtime from the value, and a variable can later refer to a different type.

python

x = 10        # int
x = "hello"   # now str
x = 10        # int
x = "hello"   # now str
x = 10        # int
x = "hello"   # now str

Q4. What is PEP 8?
Python’s style guide for writing readable code: 4-space indentation, naming conventions (snake_case for functions and variables, PascalCase for classes), line length guidance and so on.

Q5. How is Python different from Java?

Point

Python

Java

Typing

Dynamic

Static

Syntax

Shorter, indentation-based

More verbose, braces

Execution

Bytecode on Python VM

Bytecode on JVM

Compilation step

Implicit

Explicit (javac)

Common uses

Data science, scripting, automation, web

Enterprise apps, Android, backend

Q6. What are the built-in data types?
Numeric (int, float, complex), bool, str, list, tuple, set, frozenset, dict, bytes and NoneType.

Q7. What is the difference between == and is?
== compares values. is compares identity (whether two names refer to the same object).

python

a = [1, 2]
b = [1, 2]
print(a == b)   # True
print(a is b)   # False
a = [1, 2]
b = [1, 2]
print(a == b)   # True
print(a is b)   # False
a = [1, 2]
b = [1, 2]
print(a == b)   # True
print(a is b)   # False

Q8. What are mutable and immutable types? Examples?
Mutable objects can change after creation (list, dict, set). Immutable objects cannot (int, str, tuple).

Q9. What is indentation and why does it matter?
Python uses indentation to define code blocks. Incorrect indentation raises an IndentationError or changes program behaviour.

Q10. What is None?
A special object representing the absence of a value. Compare it using is None.

Q11. How do you take input and print output?

python

name = input("Enter your name: ")   # input() returns a string
age = int(input("Enter age: "))
print(f"Hello {name}, you are {age}")
name = input("Enter your name: ")   # input() returns a string
age = int(input("Enter age: "))
print(f"Hello {name}, you are {age}")
name = input("Enter your name: ")   # input() returns a string
age = int(input("Enter age: "))
print(f"Hello {name}, you are {age}")

Q12. What are f-strings?
A concise way to embed expressions in strings (Python 3.6 and later): f"Total: {price * qty}".

Trap: forgetting that input() returns a string, so arithmetic fails without conversion.

MODULE 2: STRINGS, LISTS, TUPLES, SETS, DICTIONARIES (Q13 TO Q26)

Q13. How do you reverse a string?

python

s = "python"
print(s[::-1])       # nohtyp
s = "python"
print(s[::-1])       # nohtyp
s = "python"
print(s[::-1])       # nohtyp

Q14. What is slicing?
Syntax seq[start:stop:step]. The stop index is excluded.

python

nums = [10, 20, 30, 40, 50]
print(nums[1:4])     # [20, 30, 40]
print(nums[::-1])    # [50, 40, 30, 20, 10]
nums = [10, 20, 30, 40, 50]
print(nums[1:4])     # [20, 30, 40]
print(nums[::-1])    # [50, 40, 30, 20, 10]
nums = [10, 20, 30, 40, 50]
print(nums[1:4])     # [20, 30, 40]
print(nums[::-1])    # [50, 40, 30, 20, 10]

Q15. Difference between list and tuple?

Point

List

Tuple

Mutability

Mutable

Immutable

Syntax

[ ]

( )

Performance

Slightly more overhead

Usually lighter

Use case

Changing collections

Fixed records, dictionary keys

Q16. Difference between list, set and dictionary?
A list is an ordered collection allowing duplicates. A set is a collection of unique items. A dictionary stores key-value pairs with unique keys.

Q17. What is a list comprehension? Give an example.

python

squares = [x * x for x in range(1, 6)]            # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]      # [0, 2, 4, 6, 8]
squares = [x * x for x in range(1, 6)]            # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]      # [0, 2, 4, 6, 8]
squares = [x * x for x in range(1, 6)]            # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]      # [0, 2, 4, 6, 8]

Q18. What are dictionary and set comprehensions?

python

sq = {x: x * x for x in range(1, 4)}    # {1: 1, 2: 4, 3: 9}
unique_lengths = {len(w) for w in ["a", "bb", "cc"]}   # {1, 2}
sq = {x: x * x for x in range(1, 4)}    # {1: 1, 2: 4, 3: 9}
unique_lengths = {len(w) for w in ["a", "bb", "cc"]}   # {1, 2}
sq = {x: x * x for x in range(1, 4)}    # {1: 1, 2: 4, 3: 9}
unique_lengths = {len(w) for w in ["a", "bb", "cc"]}   # {1, 2}

Q19. append() vs extend() vs insert()?

python

a = [1, 2]
a.append([3, 4])    # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])    # [1, 2, 3, 4]
c = [1, 3]
c.insert(1, 2)      # [1, 2, 3]
a = [1, 2]
a.append([3, 4])    # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])    # [1, 2, 3, 4]
c = [1, 3]
c.insert(1, 2)      # [1, 2, 3]
a = [1, 2]
a.append([3, 4])    # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])    # [1, 2, 3, 4]
c = [1, 3]
c.insert(1, 2)      # [1, 2, 3]

Q20. remove() vs pop() vs del?
remove(x) deletes the first occurrence of a value. pop(i) removes and returns the element at an index (last by default). del a[i] deletes by index or slice.

Q21. Why can a list not be a dictionary key, but a tuple can?
Dictionary keys must be hashable. Lists are mutable and not hashable. A tuple is hashable if all of its elements are hashable.

Q22. How do you remove duplicates from a list?

python

nums = [1, 2, 2, 3, 1]
print(list(set(nums)))                 # order not guaranteed
print(list(dict.fromkeys(nums)))       # [1, 2, 3] keeps first-seen order
nums = [1, 2, 2, 3, 1]
print(list(set(nums)))                 # order not guaranteed
print(list(dict.fromkeys(nums)))       # [1, 2, 3] keeps first-seen order
nums = [1, 2, 2, 3, 1]
print(list(set(nums)))                 # order not guaranteed
print(list(dict.fromkeys(nums)))       # [1, 2, 3] keeps first-seen order

Q23. How do you merge two dictionaries?

python

a = {"x": 1}
b = {"y": 2}
merged = {**a, **b}        # {'x': 1, 'y': 2}
# merged = a | b           # Python 3.9+
a = {"x": 1}
b = {"y": 2}
merged = {**a, **b}        # {'x': 1, 'y': 2}
# merged = a | b           # Python 3.9+
a = {"x": 1}
b = {"y": 2}
merged = {**a, **b}        # {'x': 1, 'y': 2}
# merged = a | b           # Python 3.9+

Q24. How do you safely read a missing key from a dictionary?

python

d = {"a": 1}
print(d.get("b"))          # None
print(d.get("b", 0))       # 0
d = {"a": 1}
print(d.get("b"))          # None
print(d.get("b", 0))       # 0
d = {"a": 1}
print(d.get("b"))          # None
print(d.get("b", 0))       # 0

Q25. What are common string methods?
upper(), lower(), strip(), split(), join(), replace(), find(), startswith(), endswith(), isdigit(), isalpha().

python

words = "a,b,c".split(",")        # ['a', 'b', 'c']
print("-".join(words))            # a-b-c
words = "a,b,c".split(",")        # ['a', 'b', 'c']
print("-".join(words))            # a-b-c
words = "a,b,c".split(",")        # ['a', 'b', 'c']
print("-".join(words))            # a-b-c

Q26. What is the time complexity of membership checks?
On average, x in list is O(n), while x in set and x in dict are O(1). That’s why sets are preferred for fast lookups.

Trap: modifying a list while looping over it, which causes skipped elements.

MODULE 3: FUNCTIONS, SCOPE, LAMBDA, DECORATORS, GENERATORS (Q27 TO Q38)

Q27. How do you define a function with default arguments?

python

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"

Q28. What are *args and **kwargs?

python

def demo(*args, **kwargs):
    print(args)      # tuple of positional arguments
    print(kwargs)    # dict of keyword arguments

demo(1, 2, a=3)      # (1, 2)  {'a': 3}
def demo(*args, **kwargs):
    print(args)      # tuple of positional arguments
    print(kwargs)    # dict of keyword arguments

demo(1, 2, a=3)      # (1, 2)  {'a': 3}
def demo(*args, **kwargs):
    print(args)      # tuple of positional arguments
    print(kwargs)    # dict of keyword arguments

demo(1, 2, a=3)      # (1, 2)  {'a': 3}

Q29. What is the mutable default argument trap?

python

def add(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add(1))   # [1]
print(add(2))   # [1, 2]  <-- surprise
def add(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add(1))   # [1]
print(add(2))   # [1, 2]  <-- surprise
def add(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add(1))   # [1]
print(add(2))   # [1, 2]  <-- surprise

The default list is created once when the function is defined. Fix it:

python

def add(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket
def add(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket
def add(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

Q30. What is a lambda function?
A small anonymous function: square = lambda x: x * x. Often used with map, filter and sorted.

python

nums = [3, 1, 2]
print(sorted(nums, key=lambda x: -x))              # [3, 2, 1]
print(list(map(lambda x: x * 2, nums)))            # [6, 2, 4]
print(list(filter(lambda x: x > 1, nums)))         # [3, 2]
nums = [3, 1, 2]
print(sorted(nums, key=lambda x: -x))              # [3, 2, 1]
print(list(map(lambda x: x * 2, nums)))            # [6, 2, 4]
print(list(filter(lambda x: x > 1, nums)))         # [3, 2]
nums = [3, 1, 2]
print(sorted(nums, key=lambda x: -x))              # [3, 2, 1]
print(list(map(lambda x: x * 2, nums)))            # [6, 2, 4]
print(list(filter(lambda x: x > 1, nums)))         # [3, 2]

Q31. Explain variable scope (LEGB).
Python looks up names in this order: Local, Enclosing, Global, Built-in.

Q32. What do global and nonlocal do?
global lets a function modify a module-level variable. nonlocal lets a nested function modify a variable in its enclosing function.

Q33. What is recursion? Example?

python

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))   # 120
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))   # 120
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))   # 120

Python limits recursion depth, so very deep recursion raises RecursionError.

Q34. What is a decorator?
A function that wraps another function to add behaviour without changing its code.

python

def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_calls
def add(a, b):
    return a + b

print(add(2, 3))
# Calling add
# 5
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_calls
def add(a, b):
    return a + b

print(add(2, 3))
# Calling add
# 5
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_calls
def add(a, b):
    return a + b

print(add(2, 3))
# Calling add
# 5

Q35. What is a generator and how is it different from a list?
A generator produces values lazily, one at a time, using yield. It saves memory because it doesn’t build the whole sequence.

python

def count_up(n):
    for i in range(1, n + 1):
        yield i

for x in count_up(3):
    print(x)          # 1 2 3

gen = (x * x for x in range(1000000))   # generator expression, low memory
def count_up(n):
    for i in range(1, n + 1):
        yield i

for x in count_up(3):
    print(x)          # 1 2 3

gen = (x * x for x in range(1000000))   # generator expression, low memory
def count_up(n):
    for i in range(1, n + 1):
        yield i

for x in count_up(3):
    print(x)          # 1 2 3

gen = (x * x for x in range(1000000))   # generator expression, low memory

Q36. yield vs return?
return ends the function and gives one result. yield pauses the function, returns a value and resumes from the same point on the next request.

Q37. What is an iterator?
An object with __iter__() and __next__() methods. Lists, tuples and strings are iterable, and iter() gives an iterator.

Q38. What are map, filter and reduce?
map applies a function to each item. filter keeps items for which a function returns true. reduce (from functools) combines items into one value.

python

from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3, 4]))   # 10
from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3, 4]))   # 10
from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3, 4]))   # 10

Trap: forgetting that a generator can be consumed only once.

MODULE 4: OOP IN PYTHON (Q39 TO Q47)

Q39. How do you define a class and create an object?

python

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def intro(self):
        return f"{self.name}, {self.age}"

s = Student("Amit", 22)
print(s.intro())
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def intro(self):
        return f"{self.name}, {self.age}"

s = Student("Amit", 22)
print(s.intro())
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def intro(self):
        return f"{self.name}, {self.age}"

s = Student("Amit", 22)
print(s.intro())

Q40. What is self?
A reference to the current instance. By convention it’s the first parameter of instance methods.

Q41. What is __init__?
The initialiser method called when an object is created. It sets up the object’s attributes.

Q42. What are the four OOP pillars in Python?
Encapsulation, inheritance, polymorphism and abstraction.

Q43. How does inheritance work? What is super()?

python

class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return super().speak() + " -> Woof"

print(Dog().speak())    # Some sound -> Woof
class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return super().speak() + " -> Woof"

print(Dog().speak())    # Some sound -> Woof
class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return super().speak() + " -> Woof"

print(Dog().speak())    # Some sound -> Woof

Q44. Does Python support multiple inheritance? What is MRO?
Yes. The Method Resolution Order (MRO) defines the order in which base classes are searched. You can view it with ClassName.__mro__.

Q45. @staticmethod vs @classmethod vs instance method?

Type

First parameter

Access

Instance method

self

Instance and class data

@classmethod

cls

Class data

@staticmethod

None

Neither; a utility function inside the class

Q46. What is encapsulation? Does Python have private variables?
Python has no strict private keyword. By convention, _name means “internal use” and __name triggers name mangling to discourage outside access.

Q47. What are dunder (magic) methods? Examples?
Special methods with double underscores, such as __init__, __str__, __repr__, __len__, __eq__ and __add__.

python

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __str__(self):
        return f"Point({self.x}, {self.y})"

print(Point(1, 2))   # Point(1, 2)
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __str__(self):
        return f"Point({self.x}, {self.y})"

print(Point(1, 2))   # Point(1, 2)
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __str__(self):
        return f"Point({self.x}, {self.y})"

print(Point(1, 2))   # Point(1, 2)

Trap: forgetting self in method definitions.

MODULE 5: EXCEPTIONS, FILES, MODULES AND TOOLS (Q48 TO Q54)

Q48. How does exception handling work

python

try:
    n = int(input("Number: "))
    print(10 / n)
except ValueError:
    print("Enter a valid integer")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("No error")
finally:
    print("Always runs")
try:
    n = int(input("Number: "))
    print(10 / n)
except ValueError:
    print("Enter a valid integer")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("No error")
finally:
    print("Always runs")
try:
    n = int(input("Number: "))
    print(10 / n)
except ValueError:
    print("Enter a valid integer")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("No error")
finally:
    print("Always runs")

Q49. What are else and finally in try?
else runs only if no exception occurred. finally always runs, which makes it useful for cleanup.

Q50. How do you raise your own exception?

python

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")

Q51. How do you read and write files safely?

python

with open("data.txt", "w") as f:
    f.write("Hello")

with open("data.txt", "r") as f:
    print(f.read())
with open("data.txt", "w") as f:
    f.write("Hello")

with open("data.txt", "r") as f:
    print(f.read())
with open("data.txt", "w") as f:
    f.write("Hello")

with open("data.txt", "r") as f:
    print(f.read())

The with statement closes the file automatically, even if an error occurs.

Q52. What is a context manager?
An object that defines setup and cleanup via __enter__ and __exit__, used with the with statement.

Q53. What are modules and packages? What does if __name__ == "__main__" do?
A module is a .py file. A package is a folder of modules. The __name__ check lets code run only when the file is executed directly, not when imported.

Q54. What are pip and virtual environments?
pip installs packages. A virtual environment (python -m venv venv) isolates a project’s dependencies from other projects.

MODULE 6: ADVANCED CONCEPTS FRESHERS ARE ASKED (Q55 TO Q60)

Q55. Shallow copy vs deep copy?

python

import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

a[0].append(99)
print(shallow)   # [[1, 2, 99], [3, 4]]  shares inner lists
print(deep)      # [[1, 2], [3, 4]]      independent
import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

a[0].append(99)
print(shallow)   # [[1, 2, 99], [3, 4]]  shares inner lists
print(deep)      # [[1, 2], [3, 4]]      independent
import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

a[0].append(99)
print(shallow)   # [[1, 2, 99], [3, 4]]  shares inner lists
print(deep)      # [[1, 2], [3, 4]]      independent

Q56. What is the GIL?
In standard CPython, the Global Interpreter Lock lets only one thread execute Python bytecode at a time. Threads help with I/O-bound work, while CPU-bound work often uses multiprocessing. Newer Python releases include experimental builds without the GIL, so check the documentation for your version.

Q57. Threading vs multiprocessing?
Threads share memory within one process and suit I/O-bound tasks. Multiprocessing uses separate processes and can use multiple CPU cores for CPU-bound tasks.

Q58. What is memory management in Python?
Python manages memory automatically using reference counting plus a garbage collector for cyclic references.

Q59. What are type hints?

python

def add(a: int, b: int) -> int:
    return a + b
def add(a: int, b: int) -> int:
    return a + b
def add(a: int, b: int) -> int:
    return a + b

Type hints document expected types and help tools. They aren’t enforced at runtime by default.

Q60. What is match / case?
Structural pattern matching, available from Python 3.10, which lets you match values and shapes.

python

def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Other"
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Other"
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Other"

MODULE 7: NUMPY AND PANDAS BASICS (FOR PYTHON + DATA SCIENCE FRESHERS)

Q61. NumPy array vs Python list?
NumPy arrays hold elements of the same type and support fast, vectorised numerical operations. Lists can hold mixed types and are more flexible but typically slower for numerical work.

python

import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)       # [2 4 6]
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)       # [2 4 6]
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)       # [2 4 6]

Q62. What is a Pandas Series and DataFrame?
A Series is a one-dimensional labelled array. A DataFrame is a two-dimensional table of rows and columns.

Q63. How do you load and inspect a CSV file?

python

import pandas as pd
df = pd.read_csv("students.csv")
print(df.head())      # first rows
print(df.info())      # column types and null counts
print(df.describe())  # summary statistics
import pandas as pd
df = pd.read_csv("students.csv")
print(df.head())      # first rows
print(df.info())      # column types and null counts
print(df.describe())  # summary statistics
import pandas as pd
df = pd.read_csv("students.csv")
print(df.head())      # first rows
print(df.info())      # column types and null counts
print(df.describe())  # summary statistics

Q64. How do you find and handle missing values?

python

print(df.isnull().sum())          # missing count per column
df = df.dropna()                  # remove rows with missing values
df["marks"] = df["marks"].fillna(df["marks"].mean())   # fill with mean
print(df.isnull().sum())          # missing count per column
df = df.dropna()                  # remove rows with missing values
df["marks"] = df["marks"].fillna(df["marks"].mean())   # fill with mean
print(df.isnull().sum())          # missing count per column
df = df.dropna()                  # remove rows with missing values
df["marks"] = df["marks"].fillna(df["marks"].mean())   # fill with mean

Q65. loc vs iloc?
loc selects by label. iloc selects by integer position.

python

df.loc[0, "name"]     # row label 0, column "name"
df.iloc[0, 1]         # first row, second column
df.loc[0, "name"]     # row label 0, column "name"
df.iloc[0, 1]         # first row, second column
df.loc[0, "name"]     # row label 0, column "name"
df.iloc[0, 1]         # first row, second column

Q66. How do you filter and group data?

python

high = df[df["marks"] > 80]
avg_by_course = df.groupby("course")["marks"].mean()
high = df[df["marks"] > 80]
avg_by_course = df.groupby("course")["marks"].mean()
high = df[df["marks"] > 80]
avg_by_course = df.groupby("course")["marks"].mean()

Q67. How do you merge two DataFrames?

python

result = pd.merge(students, courses, on="course_id", how="left")
result = pd.merge(students, courses, on="course_id", how="left")
result = pd.merge(students, courses, on="course_id", how="left")

Q68. How do you remove duplicates and sort?

python

df = df.drop_duplicates()
df = df.sort_values("marks", ascending=False)
df = df.drop_duplicates()
df = df.sort_values("marks", ascending=False)
df = df.drop_duplicates()
df = df.sort_values("marks", ascending=False)

OUTPUT PREDICTION PUZZLES (COVER THE ANSWER AND TRY FIRST)

Puzzle 1

python

print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2 == 0.3)

Output: False. Floating-point numbers are stored in binary, so small rounding errors occur. Use math.isclose() for comparisons.

Puzzle 2

python

a = [1, 2, 3]
b = a
b.append(4)
print(a)
a = [1, 2, 3]
b = a
b.append(4)
print(a)
a = [1, 2, 3]
b = a
b.append(4)
print(a)

Output: [1, 2, 3, 4]. b = a copies the reference, not the list.

Puzzle 3

python

def f(x, l=[]):
    l.append(x)
    return l

print(f(1))
print(f(2))
def f(x, l=[]):
    l.append(x)
    return l

print(f(1))
print(f(2))
def f(x, l=[]):
    l.append(x)
    return l

print(f(1))
print(f(2))

Output: [1] then [1, 2]. The mutable default argument is shared across calls.

Puzzle 4

python

print(7 // 2, -7 // 2, 7 % 3, 2 ** 3, 7 / 2)
print(7 // 2, -7 // 2, 7 % 3, 2 ** 3, 7 / 2)
print(7 // 2, -7 // 2, 7 % 3, 2 ** 3, 7 / 2)

Output: 3 -4 1 8 3.5. Floor division rounds toward negative infinity.

Puzzle 5

python

t = (1, 2, [3, 4])
t[2].append(5)
print(t)
t = (1, 2, [3, 4])
t[2].append(5)
print(t)
t = (1, 2, [3, 4])
t[2].append(5)
print(t)

Output: (1, 2, [3, 4, 5]). The tuple is immutable, but the list inside it is mutable.

Puzzle 6

python

print([] == [], [] is [])
print([] == [], [] is [])
print([] == [], [] is [])

Output: True False. Equal values, different objects.

Puzzle 7

python

d = {1: "a", 1.0: "b"}
print(d)
d = {1: "a", 1.0: "b"}
print(d)
d = {1: "a", 1.0: "b"}
print(d)

Output: {1: 'b'}. 1 and 1.0 are equal and have the same hash, so they’re the same key.

Puzzle 8

python

print(bool([]), bool("False"), bool(0), bool(" "))
print(bool([]), bool("False"), bool(0), bool(" "))
print(bool([]), bool("False"), bool(0), bool(" "))

Output: False True False True. Empty collections and zero are falsy, while non-empty strings are truthy (even “False”).

Puzzle 9

python

nums = [1, 2, 3, 4]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
nums = [1, 2, 3, 4]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
nums = [1, 2, 3, 4]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)

Output: [1, 3] in this case, but it’s a bad pattern: modifying a list while iterating can skip elements. Use a comprehension to build a new list.

Puzzle 10

python

x = "python"
print(x[1:4], x[-1], x[::2])
x = "python"
print(x[1:4], x[-1], x[::2])
x = "python"
print(x[1:4], x[-1], x[::2])

Output: yth n pto.

15 CODING PROBLEMS WITH SOLUTIONS

1. Check if a string is a palindrome

python

def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]

print(is_palindrome("Madam"))   # True
def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]

print(is_palindrome("Madam"))   # True
def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]

print(is_palindrome("Madam"))   # True

2. Fibonacci series (first n numbers)

python

def fib(n):
    a, b = 0, 1
    result = []
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result

print(fib(8))   # [0, 1, 1, 2, 3, 5, 8, 13]
def fib(n):
    a, b = 0, 1
    result = []
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result

print(fib(8))   # [0, 1, 1, 2, 3, 5, 8, 13]
def fib(n):
    a, b = 0, 1
    result = []
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result

print(fib(8))   # [0, 1, 1, 2, 3, 5, 8, 13]

3. Count vowels in a string

python

def count_vowels(s):
    return sum(1 for ch in s.lower() if ch in "aeiou")

print(count_vowels("Interview"))   # 4
def count_vowels(s):
    return sum(1 for ch in s.lower() if ch in "aeiou")

print(count_vowels("Interview"))   # 4
def count_vowels(s):
    return sum(1 for ch in s.lower() if ch in "aeiou")

print(count_vowels("Interview"))   # 4

4. Find duplicates in a list

python

def find_duplicates(nums):
    seen, dups = set(), set()
    for n in nums:
        if n in seen:
            dups.add(n)
        seen.add(n)
    return list(dups)

print(find_duplicates([1, 2, 3, 2, 4, 1]))   # [1, 2] (order may vary)
def find_duplicates(nums):
    seen, dups = set(), set()
    for n in nums:
        if n in seen:
            dups.add(n)
        seen.add(n)
    return list(dups)

print(find_duplicates([1, 2, 3, 2, 4, 1]))   # [1, 2] (order may vary)
def find_duplicates(nums):
    seen, dups = set(), set()
    for n in nums:
        if n in seen:
            dups.add(n)
        seen.add(n)
    return list(dups)

print(find_duplicates([1, 2, 3, 2, 4, 1]))   # [1, 2] (order may vary)

5. Two-sum (indices of two numbers adding to a target)

python

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in seen:
            return [seen[need], i]
        seen[n] = i
    return []

print(two_sum([2, 7, 11, 15], 9))   # [0, 1]
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in seen:
            return [seen[need], i]
        seen[n] = i
    return []

print(two_sum([2, 7, 11, 15], 9))   # [0, 1]
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in seen:
            return [seen[need], i]
        seen[n] = i
    return []

print(two_sum([2, 7, 11, 15], 9))   # [0, 1]

Complexity: O(n) time using a dictionary.

6. Check for anagrams

python

def is_anagram(a, b):
    return sorted(a.lower()) == sorted(b.lower())

print(is_anagram("listen", "silent"))   # True
def is_anagram(a, b):
    return sorted(a.lower()) == sorted(b.lower())

print(is_anagram("listen", "silent"))   # True
def is_anagram(a, b):
    return sorted(a.lower()) == sorted(b.lower())

print(is_anagram("listen", "silent"))   # True

7. FizzBuzz

python

for i in range(1, 16):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
for i in range(1, 16):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
for i in range(1, 16):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

8. Word frequency count

python

from collections import Counter

text = "to be or not to be"
print(Counter(text.split()))
# Counter({'to': 2, 'be': 2, 'or': 1, 'not': 1})
from collections import Counter

text = "to be or not to be"
print(Counter(text.split()))
# Counter({'to': 2, 'be': 2, 'or': 1, 'not': 1})
from collections import Counter

text = "to be or not to be"
print(Counter(text.split()))
# Counter({'to': 2, 'be': 2, 'or': 1, 'not': 1})

9. Remove duplicates while keeping order

python

nums = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(nums)))   # [3, 1, 2]
nums = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(nums)))   # [3, 1, 2]
nums = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(nums)))   # [3, 1, 2]

10. Find the second largest number

python

def second_largest(nums):
    unique = sorted(set(nums))
    return unique[-2] if len(unique) >= 2 else None

print(second_largest([10, 20, 20, 5]))   # 10
def second_largest(nums):
    unique = sorted(set(nums))
    return unique[-2] if len(unique) >= 2 else None

print(second_largest([10, 20, 20, 5]))   # 10
def second_largest(nums):
    unique = sorted(set(nums))
    return unique[-2] if len(unique) >= 2 else None

print(second_largest([10, 20, 20, 5]))   # 10

11. Check if a number is prime

python

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(29))   # True
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(29))   # True
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(29))   # True

12. Flatten a nested list (one level)

python

nested = [[1, 2], [3], [4, 5]]
flat = [x for sub in nested for x in sub]
print(flat)   # [1, 2, 3, 4, 5]
nested = [[1, 2], [3], [4, 5]]
flat = [x for sub in nested for x in sub]
print(flat)   # [1, 2, 3, 4, 5]
nested = [[1, 2], [3], [4, 5]]
flat = [x for sub in nested for x in sub]
print(flat)   # [1, 2, 3, 4, 5]

13. Count characters using a dictionary

python

s = "hello"
counts = {}
for ch in s:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)   # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
s = "hello"
counts = {}
for ch in s:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)   # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
s = "hello"
counts = {}
for ch in s:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)   # {'h': 1, 'e': 1, 'l': 2, 'o': 1}

14. Swap two variables

python

a, b = 5, 10
a, b = b, a
print(a, b)   # 10 5
a, b = 5, 10
a, b = b, a
print(a, b)   # 10 5
a, b = 5, 10
a, b = b, a
print(a, b)   # 10 5

15. Read a file and count its lines

python

with open("data.txt") as f:
    print(sum(1 for _ in f))
with open("data.txt") as f:
    print(sum(1 for _ in f))
with open("data.txt") as f:
    print(sum(1 for _ in f))

Tip: explain your approach aloud before writing code, mention time complexity, and test with a small example.

SCENARIO AND PROJECT QUESTIONS

Question

A solid approach

“Walk me through a Python project you built.”

Problem, tools, your role, one challenge, what you learned. Be ready for code-level follow-ups.

“Your script is slow. What would you check?”

Algorithm choice, unnecessary loops, data structures (set vs list), reading files in chunks, using vectorised Pandas or NumPy operations.

“How do you handle a CSV with missing values?”

Inspect with isnull().sum(), decide whether to drop, fill with a statistic or investigate the source.

“How would you structure a small Python project?”

Separate modules, a requirements.txt, a virtual environment, tests and a README.

“How do you debug Python code?”

Read the traceback, use print or logging, use a debugger, reproduce with a small input.

“Python 2 vs Python 3?”

Python 2 is no longer supported. New work uses Python 3.

COMMON MISTAKES FRESHERS MAKE IN PYTHON INTERVIEWS

Mistake

Better approach

Memorising answers without running code

Run every example yourself

Confusing == and is

== compares values, is compares identity

Mutable default arguments

Use None and create inside the function

Not knowing project code

Only list projects you can explain line by line

Ignoring edge cases (empty input, negatives)

State them before coding

Using lists where sets or dictionaries are faster

Mention time complexity

Over-claiming skills (Django, ML)

List only what you’ve actually practised

Writing code without explaining

Think aloud and explain your approach

MYTH VS REALITY

Myth

Reality

“Python is easy, so interviews are easy.”

Interviews test concepts, problem solving and clean code, not just syntax.

“I only need data science libraries.”

Core Python (data structures, functions, OOP) is tested first.

“Memorising 100 questions is enough.”

Interviewers follow up on your answers and projects.

“Python is slow so it’s not used in jobs.”

Python is widely used for automation, data work and backend services. Speed-critical parts are often handled by optimised libraries.

“Freshers can’t get Python roles without experience.”

A few good projects, clear fundamentals and honest answers can help, though results vary.

A 14-DAY PYTHON INTERVIEW PREPARATION PLAN

Day

Focus

Task

1

Basics, data types, operators

Practise Q1 to Q12

2

Strings and slicing

Solve 5 string problems

3

Lists and tuples

Practise Q15 to Q22

4

Sets and dictionaries

Practise Q23 to Q26, word-count problems

5

Functions, *args, **kwargs, lambda

Practise Q27 to Q33

6

Decorators, generators, iterators

Write one of each from scratch

7

Revision and output puzzles

Solve all 10 puzzles without running them first

8

OOP basics

Build a small class hierarchy

9

Exceptions and file handling

Read, write and handle errors in a text file

10

Modules, pip, virtual environments

Set up a clean project folder

11

NumPy and Pandas basics

Clean and summarise a small CSV

12

Coding problems

Solve 5 problems from the list above

13

Project preparation

Prepare a 3-minute project explanation

14

Mock interview

Answer 20 random questions aloud

WHICH PYTHON ROLES CAN FRESHERS TARGET?

Role

Typical Python focus

Python developer (junior)

Core Python, OOP, frameworks like Django or Flask, APIs, databases

Data analyst (fresher)

Python, SQL, Pandas, Excel, visualisation

Data science trainee

Python, statistics basics, NumPy, Pandas, machine learning basics

Automation or scripting engineer

Python scripting, APIs, file handling, testing

QA automation (with Python)

Python, test frameworks, Selenium

Check each job description for the exact skills before you apply.

HOW VIBRANTMINDS HELPS FRESHERS PREPARE FOR PYTHON AND DATA SCIENCE ROLES

VibrantMinds Technologies Pvt. Ltd. is a Pune-based IT training and placement support company. If you searched for VibrantMinds or VibrantMinds Technologies, here is what it offers:

  • Python & Data Science training (about 2 to 4 months): Python basics, data handling and analysis fundamentals. Please check the candidate portal for the latest syllabus.

  • Full Stack Java Development (about 4 to 6 months), Core Java (about 1 to 2 months) and Software Testing (Manual + Automation) for other career paths

  • Project practice: Build a small data or automation project you can explain in interviews

  • Interview preparation: Technical rounds, HR rounds, aptitude, communication and mock interviews

  • Placement support: Screening, drive coordination and interview support. Check the campus-drives portal at https://candidates.vibrantminds.in/ for current openings.

  • Free WhatsApp job alert groups for fresher IT jobs and drives

  • Honesty first: VibrantMinds offers placement support, not a guaranteed job, and no legitimate recruiter should ask you to pay to be interviewed.

VibrantMinds works as a talent ecosystem connecting candidates, colleges and companies, with 1900+ partner colleges and 600+ hiring companies. Read more fresher job guidance here: https://candidates.vibrantminds.in/blog/fresher-jobs-pune-2026

VIBRANTMINDS COURSES AT A GLANCE

Course

Duration

Key topics

Python & Data Science

2 to 4 months

Python basics, data handling, analysis fundamentals

Full Stack Java Development

4 to 6 months

Core Java, OOP, JDBC, SQL, Spring Boot, REST APIs, front-end basics, projects, aptitude and interview preparation

Software Testing (Manual + Automation)

2 to 5 months

Test cases, STLC, bug tracking, SQL, Selenium basics

Core Java

1 to 2 months

Syntax, OOP, collections, exceptions, strings

Fees, syllabus and batch dates are on https://candidates.vibrantminds.in/. Please confirm them directly before enrolling.

THE VIBRANTMINDS PLACEMENT PIPELINE: SIX STEPS




REAL OUTCOMES: WHAT TO EXPECT AND WHAT NOT TO

Past students have shared positive feedback about the training and support, and have gone on to roles at companies such as Aress Software and Education Technologies, Saama Technologies and Three M Software. Results vary by candidate, skill level, effort and market conditions, so please confirm details directly with the VibrantMinds team. No one can honestly promise a guaranteed job.

JOIN FREE VIBRANTMINDS WHATSAPP GROUPS: FRESHER IT JOB UPDATES FOR PUNE AND INDIA

Looking for free WhatsApp groups for IT jobs, a Java WhatsApp group for freshers or a job updates WhatsApp group in India? The VibrantMinds groups share fresher IT openings, campus drives, walk-in interview alerts and interview preparation updates, free of charge. Join whichever group has space. All three carry the same type of updates.

Group

What it offers

Link

VibrantMinds Fresher IT Jobs, Group 1

Fresher openings, campus drives, walk-in alerts

https://chat.whatsapp.com/CUCS1derlmTFee2c9dyUHd

VibrantMinds Fresher IT Jobs, Group 2

Fresher openings, campus drives, walk-in alerts

https://chat.whatsapp.com/FvMf1fGYQYnHppQ8AwFX40

VibrantMinds Fresher IT Jobs, Group 3

Fresher openings, campus drives, walk-in alerts

https://chat.whatsapp.com/I7RNnGMkb2L8S8HibdyWpQ

Never pay to apply. Legitimate recruiters do not charge candidates for tests, interviews or offer letters. Do not share sensitive personal or financial details in any group chat.

FREQUENTLY ASKED QUESTIONS

1. What are the most asked Python interview questions for freshers?
Differences between list, tuple, set and dictionary, mutable vs immutable types, == vs is, *args and **kwargs, list comprehensions, decorators and generators, OOP concepts, exception handling, file handling and basic coding problems such as palindrome, Fibonacci and finding duplicates.

2. How do I prepare for a Python interview as a fresher?
Revise core concepts, run every code example yourself, solve 15 to 20 coding problems, practise output-prediction questions, prepare your projects, and do mock interviews. The 14-day plan above gives a day-by-day schedule.

3. Are Pandas and NumPy asked in fresher Python interviews?
For data analyst and data science roles, yes: expect questions on DataFrames, loc vs iloc, handling missing values, groupby and merge. For general Python developer roles, core Python and OOP matter more.

4. Is Python enough to get a job as a fresher?
Python alone is rarely enough. Employers also look for problem solving, SQL, Git, projects, and role-specific skills such as a web framework or data libraries. Results vary by candidate and market conditions.

5. Are there free WhatsApp groups for IT fresher jobs in Pune?
Yes. VibrantMinds runs free fresher IT job WhatsApp groups that share openings, campus drives and walk-in alerts. Join through the links above. Always verify any job post and never pay to apply.

CONCLUSION: PRACTISE, DON’T JUST MEMORISE

The best way to prepare for Python interview questions for freshers is to write and run code every day. Master the cheat sheet, understand mutability and the common traps, solve the coding problems, and build one project you can explain confidently. Be honest about what you know, think aloud while coding and keep learning.

If you’re in Pune and want guided Python, Java or testing training with project practice, interview preparation and placement support, VibrantMinds Technologies is here to help.

Call to action:

VISIT OR CONTACT VIBRANTMINDS IN PUNE

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved