VibrantMinds Logo
VibrantMinds
Back to Blog
Oct 23, 2026 👁️ 42 Views

Python Interview Questions and Answers for Freshers (With Code Examples)

If you are preparing for a Python developer, data analyst or testing interview, Python interview questions for freshers are the best place to start. Python is used for backend development, automation, data analysis and machine learning, so fresher interviews usually test the same core ideas: data types, data structures, functions, object-oriented programming, exception handling and a few small coding problems. This guide covers those questions with clear answers, runnable code and the exact output, so you can practise instead of memorising.

Questions are grouped by topic, from basics and data structures to functions, OOP, exceptions, modules and coding problems. It also includes a seven-day preparation plan and a list of common mistakes. Every example is plain Python 3, so you can paste it into any editor or online interpreter and run it yourself.

Quick answer: The Python topics freshers are asked most are mutable vs immutable types, list vs tuple vs set vs dict, list comprehensions, *args and kwargs, decorators and generators, OOP basics, exception handling, and small coding problems such as palindromes, Fibonacci and word frequency. Run every example yourself.

 

Explore VibrantMinds

VibrantMinds Technologies is a Pune-based IT training and recruitment company. Learn more about its courses and placement process, or visit the candidate portal.

vibrantminds.in   |   candidates.vibrantminds.in

What Python Topics Do Interviewers Ask Freshers?

The depth depends on the role, but the main areas are consistent:

•       Basics: features of Python, dynamic typing, mutable vs immutable, is vs ==, type conversion.

•       Data structures: list, tuple, set, dictionary, slicing, comprehensions, copying.

•       Functions: *args and kwargs, lambda, map and filter, decorators, generators, scope.

•       OOP: classes, __init__, inheritance, polymorphism, static and class methods.

•       Exceptions and files: try-except, custom exceptions, the with statement.

•       Libraries and tools: modules, packages, pip, virtual environments, NumPy and Pandas basics.

•       Coding problems: strings, lists, loops and simple logic.

Data analyst roles lean towards Pandas and SQL, testers towards scripting and automation, and developers towards OOP and frameworks. In every case the fundamentals below are the foundation.

Python Basics Interview Questions for Freshers

Q1. What is Python, and what are its main features?

Python is a high-level, general-purpose programming language known for readable syntax. Its main features are simple and clear syntax, dynamic typing, automatic memory management, support for object-oriented, procedural and functional styles, a large standard library and a huge ecosystem of third-party packages.

Q2. Is Python interpreted or compiled?

Both, in a sense. In the standard CPython implementation, your source code is first compiled to bytecode, which the Python Virtual Machine then executes. People call Python "interpreted" because you do not run a separate compile step yourself.

Q3. What does dynamically typed mean?

You do not declare a variable's type. The type belongs to the value, and a variable can later refer to a value of a different type. Python is still strongly typed: it will not silently mix incompatible types, so adding a number to a string raises an error.

PYTHON

x = 10          # int

x = "ten"       # now a str; allowed

print("5" + 3)  # TypeError: can only concatenate str to str

Q4. What is the difference between mutable and immutable types?

A mutable object can be changed after it is created: list, dict and set are mutable. An immutable object cannot: int, float, str, bool and tuple are immutable. Operations on immutable objects, such as upper() on a string, return a new object instead of changing the original.


PYTHON

t = (1, 2, 3)

t[0] = 9          # TypeError: 'tuple' object does not support item assignment

 

nums = [1, 2, 3]

nums[0] = 9       # fine: [9, 2, 3]

Q5. What is the difference between == and is?

== compares values (equality). is compares identity, meaning whether both names refer to the very same object in memory.

PYTHON

a = [1, 2]

b = [1, 2]

c = a

 

print(a == b)   # True   (same contents)

print(a is b)   # False  (two different objects)

print(a is c)   # True   (same object)

 

Q6. How does Python manage memory?

Python manages memory automatically. In CPython, a private heap holds all objects, and memory is reclaimed mainly through reference counting: when nothing refers to an object any more, it is freed. A garbage collector also detects and cleans up groups of objects that refer to each other in cycles. You do not free memory manually.

Q7. What is PEP 8?

PEP 8 is the official style guide for writing readable Python code. It recommends four-space indentation, snake_case for variable and function names, CapWords for class names, and sensible line lengths. Following it makes your code easier to read in interviews and in teams.

Q8. What is the role of indentation in Python?

Indentation defines code blocks. Unlike languages that use braces, Python uses consistent indentation (four spaces is the convention) to mark what belongs inside an if, loop, function or class. Wrong indentation causes an IndentationError or changes the program's logic.

Python Data Structures Interview Questions

Q9. What is the difference between a list, tuple, set and dictionary?

•       List: ordered, changeable, allows duplicates. Written with square brackets.

•       Tuple: ordered, unchangeable, allows duplicates. Written with round brackets.

•       Set: unordered, no duplicates, changeable. Written with curly braces.

•       Dictionary: key-value pairs, with unique keys. Written with curly braces and colons.

A quick way to choose between them is the decision tree below.


Q10. How does list slicing work?

Slicing uses start:stop:step. The start index is included, the stop index is excluded, and negative indexes count from the end.

PYTHON

nums = [10, 20, 30, 40, 50]

print(nums[1:4])    # [20, 30, 40]

print(nums[-2:])    # [40, 50]

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

 

Q11. What is a list comprehension?

A list comprehension builds a list in one readable line from an iterable, with an optional condition. It is usually shorter and clearer than an equivalent loop.

PYTHON

squares = [n * n for n in range(1, 6)]

print(squares)   # [1, 4, 9, 16, 25]

 

evens = [n for n in range(10) if n % 2 == 0]

print(evens)     # [0, 2, 4, 6, 8]

 

Q12. How do you work with dictionaries? Show common methods.

PYTHON

d = {"name": "Asha", "age": 22}

 

print(d["name"])               # Asha

print(d.get("city", "N/A"))    # N/A (no KeyError)

 

for key, value in d.items():

    print(key, value)          # name Asha, then age 22

 

Using get() with a default avoids a KeyError when a key might be missing.

Q13. How do you remove duplicates from a list?

A set removes duplicates but does not preserve order. To keep the original order, use dict.fromkeys().

PYTHON

items = [3, 1, 3, 2, 1]

print(list(set(items)))             # duplicates removed; order not guaranteed

print(list(dict.fromkeys(items)))   # [3, 1, 2]  (order kept)

 

Q14. How do you sort a dictionary by value?

PYTHON

scores = {"A": 70, "B": 90, "C": 80}

result = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)

print(result)   # [('B', 90), ('C', 80), ('A', 70)]

 

Q15. What is the difference between shallow copy and deep copy?

A shallow copy creates a new outer object but still shares the inner objects. A deep copy copies everything recursively, so the copy is fully independent.

PYTHON

import copy

 

a = [[1, 2], [3, 4]]

b = copy.copy(a)        # shallow

c = copy.deepcopy(a)    # deep

 

a[0].append(99)

print(b[0])   # [1, 2, 99]  (inner list is shared)

print(c[0])   # [1, 2]      (independent copy)

Python Functions and OOP Interview Questions

Q16. What are *args and **kwargs?

*args collects extra positional arguments into a tuple. kwargs collects extra keyword arguments into a dictionary. They let a function accept a flexible number of arguments.

PYTHON

def show(*args, **kwargs):

    print(args)      # (1, 2, 3)

    print(kwargs)    # {'name': 'Asha'}

 

show(1, 2, 3, name="Asha")

Q17. What are lambda, map and filter?

A lambda is a small anonymous function written in one line. map() applies a function to every item, and filter() keeps the items for which a function returns True. Both return iterators, so wrap them in list() to see the results.

PYTHON

nums = [1, 2, 3, 4, 5]

print(list(map(lambda n: n * 2, nums)))          # [2, 4, 6, 8, 10]

print(list(filter(lambda n: n % 2 == 1, nums)))  # [1, 3, 5]

Q18. What is a decorator?

A decorator is a function that takes another function and extends its behaviour without changing its code. It is applied with the @ symbol and is widely used for logging, timing and access control.

PYTHON

def log_call(func):

    def wrapper(*args, **kwargs):

        print("Calling", func.__name__)

        return func(*args, **kwargs)

    return wrapper

 

@log_call

def add(a, b):

    return a + b

 

print(add(2, 3))

# Calling add

# 5

Q19. What is a generator, and how is yield different from return?

A generator produces values one at a time, pausing at each yield and resuming where it left off. It uses very little memory because it does not build the whole sequence. return ends the function, while yield pauses it.

PYTHON

def count_up(n):

    i = 1

    while i <= n:

        yield i

        i += 1

 

for x in count_up(3):

    print(x)     # 1, then 2, then 3

Q20. What is variable scope? Explain the LEGB rule.

Scope decides where a name can be used. When Python sees a name, it searches Local, then Enclosing, then Global, then Built-in scope, and uses the first match.


PYTHON

x = "global"

 

def outer():

    x = "enclosing"

    def inner():

        x = "local"

        print(x)       # local

    inner()

    print(x)           # enclosing

 

outer()

print(x)               # global

 

Q21. What is the mutable default argument problem?

A default value is created once, when the function is defined. If it is mutable, such as a list, every call shares and changes the same object. This is a very common interview trap.

PYTHON

def add_item(item, items=[]):

    items.append(item)

    return items

 

print(add_item(1))   # [1]

print(add_item(2))   # [1, 2]   <- the same list was reused

 

# Fix: use None as the default

def add_item(item, items=None):

    if items is None:

        items = []

    items.append(item)

    return items

 

Q22. What are classes and objects? What does __init__ do?

A class is a blueprint; an object is an instance created from it. __init__ is the initialiser method that runs when an object is created and sets its starting attributes. self refers to the current object.

PYTHON

class Student:

    def __init__(self, name, marks):

        self.name = name

        self.marks = marks

 

    def __str__(self):

        return f"{self.name}: {self.marks}"

 

s = Student("Asha", 85)

print(s)    # Asha: 85

 

Q23. How do inheritance and method overriding work in Python?

A child class inherits attributes and methods from its parent. It can override a method by defining one with the same name, and the child's version runs. Python also supports multiple inheritance, using the Method Resolution Order (MRO) to decide which parent is checked first.

PYTHON

class Animal:

    def sound(self):

        return "Some sound"

 

class Dog(Animal):

    def sound(self):          # overrides the parent method

        return "Bark"

 

print(Dog().sound())   # Bark

Q24. What is the difference between @staticmethod and @classmethod?

A classmethod receives the class as its first argument (cls) and can read or change class-level data. A staticmethod receives neither the class nor an instance. It is just a utility function that lives inside the class.

PYTHON

class Employee:

    company = "Acme"

 

    @classmethod

    def get_company(cls):

        return cls.company

 

    @staticmethod

    def is_adult(age):

        return age >= 18

 

print(Employee.get_company())   # Acme

print(Employee.is_adult(20))    # True

Python Exception Handling and File Handling Questions

Q25. How does exception handling work? Explain try, except, else and finally.

Code that might fail goes in try. except handles specific errors. else runs only if no exception occurred, and finally always runs, which makes it the place for cleanup.

PYTHON

try:

    result = 10 / int(input("Enter a number: "))

except ZeroDivisionError:

    print("Cannot divide by zero")

except ValueError:

    print("Please enter a valid number")

else:

    print("Result:", result)

finally:

    print("Done")

 

Q26. How do you create a custom exception?

PYTHON

class InvalidAgeError(Exception):

    pass

 

def check_age(age):

    if age < 18:

        raise InvalidAgeError("Age must be 18 or above")

 

try:

    check_age(15)

except InvalidAgeError as e:

    print(e)     # Age must be 18 or above

 

Q27. What is the with statement, and why use it for files?

The with statement uses a context manager that sets up a resource and cleans it up automatically, even if an error occurs. For files, it closes the file for you, so you cannot forget.

PYTHON

with open("data.txt") as f:

    for line in f:

        print(line.strip())

Python Modules, Libraries and Data Questions

Q28. What is the difference between a module and a package?

A module is a single Python file containing code you can import. A package is a directory of related modules, traditionally marked by an __init__.py file. Packages let you organise larger projects.

Q29. What are pip and virtual environments?

pip is the tool for installing third-party packages. A virtual environment is an isolated folder with its own Python packages, so different projects can use different versions without conflict.

TERMINAL

python -m venv venv

pip install pandas

Q30. What is the difference between NumPy and Pandas?

NumPy provides fast multi-dimensional arrays for numerical computing. Pandas is built on top of it and provides DataFrames for working with labelled, tabular data such as spreadsheets and database tables. Data analyst roles usually ask at least the basics of both.

PYTHON

import pandas as pd

 

df = pd.DataFrame({"name": ["Asha", "Rohan"], "marks": [85, 72]})

print(df[df["marks"] > 80])

#    name  marks

# 0  Asha     85

Q31. What is the GIL?

The Global Interpreter Lock in CPython lets only one thread execute Python bytecode at a time. It means threads do not speed up CPU-heavy work, though they still help with waiting tasks such as network or file input and output. For CPU-bound work, use multiprocessing instead.

Python Coding Interview Questions for Freshers (With Solutions)

Explain your approach before you write code, and mention edge cases such as empty input.

Q32. How do you reverse a string?

PYTHON

s = "interview"

print(s[::-1])     # weivretni

 

Q33. How do you check whether a string is a palindrome?

PYTHON

def is_palindrome(s):

    s = s.lower()

    return s == s[::-1]

 

print(is_palindrome("Madam"))   # True

print(is_palindrome("python"))  # False

 

Q34. How do you print the Fibonacci series?

PYTHON

def fibonacci(n):

    a, b = 0, 1

    result = []

    for _ in range(n):

        result.append(a)

        a, b = b, a + b

    return result

 

print(fibonacci(7))   # [0, 1, 1, 2, 3, 5, 8]

 

Q35. How do you count the frequency of words in a sentence?

PYTHON

from collections import Counter

 

text = "python is fun and python is powerful"

print(Counter(text.split()))

# Counter({'python': 2, 'is': 2, 'fun': 1, 'and': 1, 'powerful': 1})

 

Q36. How do you find duplicate elements in a list?

PYTHON

nums = [4, 2, 7, 2, 9, 4]

seen, dups = set(), set()

 

for n in nums:

    if n in seen:

        dups.add(n)

    seen.add(n)

 

print(dups)   # {2, 4}

 

Q37. How do you find the second-largest number in a list?

PYTHON

nums = [10, 40, 30, 40, 20]

unique = sorted(set(nums), reverse=True)

print(unique[1])   # 30

 

Q38. How do you check whether 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

How to Prepare for Python Interviews in 7 Days

 

1.     Day 1: install Python, then practise variables, types, operators and conditionals.

2.     Day 2: loops, functions, *args and kwargs, and scope.

3.     Day 3: lists, tuples, sets, dictionaries, slicing and comprehensions.

4.     Day 4: OOP: classes, inheritance, overriding, static and class methods.

5.     Day 5: exceptions, file handling, decorators and generators.

6.     Day 6: solve the coding problems above from scratch, and explain each aloud.

7.     Day 7: timed mock round, then review mistakes and revise weak topics.

Common Mistakes Freshers Make in Python Interviews

 

1.     Memorising answers without running code. Run every example and change it to see what happens.

2.     Confusing == with is, or mutable with immutable behaviour.

3.     Falling for the mutable default argument trap.

4.     Writing C-style loops where a comprehension or built-in is cleaner.

5.     Ignoring edge cases, such as empty lists or zero.

6.     Not explaining the approach before writing code.

About VibrantMinds Technologies

VibrantMinds Technologies Pvt. Ltd. is a Pune-based IT training and recruitment company. It operates as a talent ecosystem that connects candidates, colleges and companies, with 1900+ partner colleges and 600+ hiring companies in its network.

Visit vibrantminds.in to learn about the company, or open the candidate portal at candidates.vibrantminds.in.

These are the VibrantMinds courses:

Course

Duration

Key topics

Full Stack Java Development

4–6 months

Core Java, OOP, SQL and JDBC, web fundamentals, backend frameworks, front-end basics, projects

Software Testing (Manual + Automation)

2–5 months

Testing fundamentals, test cases, bug reporting, SDLC and STLC, automation basics, interview preparation

Core Java

1–2 months

Syntax, OOP, strings, collections, exception handling, practice programs

Python & Data Science

2–4 months

Python basics, data handling, analysis libraries, visualisation, introduction to machine learning

How VibrantMinds Helps You Prepare for Python Interviews

The Python & Data Science course (2–4 months) lines up directly with this guide. Its topics include Python basics, data handling, analysis libraries, visualisation and an introduction to machine learning, which cover the fundamentals above and the NumPy and Pandas side of data roles. Ask the team which projects and practice sessions are part of the current batch, so you know how much hands-on coding you will get.

The VibrantMinds 6-step placement pipeline then connects your preparation to real openings:

1.     Requirement Mapping: understanding what hiring companies need, so your preparation matches real requirements.

2.     Candidate Sourcing: identifying candidates who fit those openings.

3.     Screening & Assessment: checking skills and readiness, so gaps surface before a real interview.

4.     Drive Coordination: organising recruitment drives with hiring companies.

5.     Interview Support: preparing candidates for interview rounds, including technical rounds like this one.

6.     Onboarding Follow-up: staying in touch after selection to support the joining process.

VibrantMinds tip

Not sure whether Python & Data Science, Full Stack Java or Software Testing suits your target role? Talk to the team, and ask which assessments and interview practice are part of the batch.

Visit vibrantminds.in   |   Candidate portal

Real Outcomes: What Past Students Say

Feedback shared by past students mentions placements with companies such as Aress Software and Education Technologies, Saama Technologies and Three M Software. To be clear and fair: outcomes vary from person to person, depending on skills, effort, attendance, interview performance and company requirements. Nothing here is a guarantee of a job, so please confirm details directly with the VibrantMinds team before you decide.

Connect With VibrantMinds Technologies

Address: Viva Academy Building, Warje, Pune, Maharashtra 411052

Phone: +91 95035 79517

Email: support@vibrantmindstech.com

Website: https://vibrantminds.in/

Candidate portal: https://candidates.vibrantminds.in/

Join the Job-Update WhatsApp Groups

Group 1: https://chat.whatsapp.com/CUCS1derlmTFee2c9dyUHd

Group 2: https://chat.whatsapp.com/FvMf1fGYQYnHppQ8AwFX40

Group 3: https://chat.whatsapp.com/I7RNnGMkb2L8S8HibdyWpQ

 

Caution: never pay anyone to apply for a job or to get shortlisted. If someone asks for money in exchange for a job opportunity, stop and verify directly with the company or the VibrantMinds team.

Frequently Asked Questions About Python Interviews

Is Python enough to get a job as a fresher?

It can be, depending on the role. Python developer, automation and data analyst roles usually also expect SQL, problem solving, and a few libraries or frameworks. Check the job description to see which extras your target roles list.

Which Python version should I learn?

Learn Python 3. Python 2 has been retired, and all current courses, libraries and interviews use Python 3.

How much DSA is needed for a Python fresher interview?

Many companies test basic problem solving with strings, lists, dictionaries and simple algorithms, but the depth varies by company and role. Practise the fundamentals and the coding problems in this guide.

Do I need to learn Django or Flask for fresher interviews?

For backend or full stack Python roles, basic knowledge of one framework is often expected. For data analyst or automation roles, Pandas, SQL and scripting usually matter more. The job description is the best guide.

What is the difference between Python and Java for interviews?

Both are tested on fundamentals, but Java interviews emphasise OOP structure and strong typing, while Python interviews emphasise built-in data structures, comprehensions and concise problem solving. Learn the one your target roles ask for.

Can I use built-in functions in coding rounds?

Usually yes, but some interviewers ask you to solve a problem without them to test your logic, for example reversing a string without slicing. Be ready to show both versions.

How can I practise Python for free?

Install Python on your computer, run the examples in this guide, and then change them. Many free online platforms also offer practice problems and interpreters.

Can a non-IT graduate learn Python for an IT job?

Yes, many people start from other streams. Build fundamentals, make small projects and show them. Requirements differ by company, and no outcome is guaranteed.

Final Thoughts: Run the Code, Then Explain It

Python interviews reward people who have actually run the code. Type every example, change it, break it, and predict the output before you press Enter. When you can explain why a mutable default argument misbehaves or why a tuple cannot change, you are answering the way interviewers want to hear.

If you want structured Python training with data skills, or help planning which course matches your target role, the VibrantMinds team is happy to talk it through.

Share this article:
WhatsApp LinkedIn Facebook Twitter

Launch Your IT Career

Learn Python, Java, testing, or data analytics with 100% placement assurance.

Explore Courses →

Join Live Placement Drives

Direct hiring access for top IT and multinational corporations.

Register Today →
Chat with us!