Skip to content

Python Interview Questions for Freshers (2026): 20 Questions With Answers and Code

Gulab Chand Tejwani

Gulab Chand Tejwani

PMP · PL-300 · Microsoft Certified Trainer

· 12 min read

PythonPython Interview QuestionsFreshersInterview PreparationCoding Interview
Python Interview Questions for Freshers (2026): 20 Questions With Answers and Code

Python interviews for freshers usually test four things: core data types (lists, tuples, dictionaries, sets), how Python handles mutability and references, functions and basic object-oriented programming, and one or two short coding problems you solve live. The twenty questions below cover all four, with answers short enough to say out loud and code you can run.

I'm Gulab Chand Tejwani from TechNet Consultancy. I've sat on the interviewer's side for freshers, and the thing that separates candidates is rarely knowledge of obscure features. It's whether they can explain a simple concept clearly and then write ten lines of working code without panicking. So that's what this post practises.

What do Python interviews for freshers actually test?

Most fresher rounds I've seen follow a pattern. A short screening with concept questions, then a coding round where you solve a problem in an editor or on a shared screen, sometimes followed by "how would you improve this?". For data analyst roles there's often a pandas question too. I've covered that separately in the pandas post.

Four areas tested in fresher Python interviews: data types, mutability and references, functions and OOP, live coding problems
The four areas most fresher Python interviews cover.

Core Python questions

1. What is Python, and why is it popular?

Python is a high-level, interpreted, dynamically typed programming language with a large standard library. It's popular because the syntax is readable, it runs on every major platform, and it has strong libraries for web development, automation, data analysis (pandas, NumPy) and machine learning.

2. What are Python's built-in data types?

The ones you'll use daily: int, float, bool, str, list, tuple, dict, set and None. A good interview answer groups them: numbers, text, sequences (list, tuple, str), mappings (dict) and sets.

3. What's the difference between a list and a tuple?

A list is mutable: you can add, remove and change items. A tuple is immutable: once created, it can't change. Tuples can be dictionary keys (if their items are hashable). Lists can't.

nums = [1, 2, 3]
nums.append(4)        # fine: [1, 2, 3, 4]

point = (10, 20)
# point[0] = 5        # TypeError: 'tuple' object does not support item assignment

locations = {(23.0, 72.6): "Ahmedabad"}   # a tuple works as a key

4. What does "mutable" mean, and why does it matter?

A mutable object can change after it's created (list, dict, set). An immutable one can't (int, float, str, tuple). It matters because two names can point to the same mutable object, so a change through one name shows up through the other.

a = [1, 2, 3]
b = a            # b is the same list, not a copy
b.append(4)
print(a)         # [1, 2, 3, 4]

c = a.copy()     # a new list
c.append(5)
print(a)         # still [1, 2, 3, 4]
Mutable Python types (list, dict, set) change in place; immutable types (int, float, str, tuple) create a new object when changed
Mutable objects change in place, so every name pointing at them sees the change.

5. What's the difference between == and is?

== compares values. is checks whether two names point to the same object. Use is for None checks (if x is None:) and == for everything else.

x = [1, 2]
y = [1, 2]
print(x == y)   # True, same values
print(x is y)   # False, two different lists

6. How do you remove duplicates from a list?

If order doesn't matter, convert to a set. If order matters (it usually does in an interview), use dict.fromkeys, because dictionaries keep insertion order.

items = [3, 1, 3, 2, 1]
print(list(set(items)))             # order not guaranteed
print(list(dict.fromkeys(items)))   # [3, 1, 2]

7. What is a dictionary, and how do you loop over it?

A dictionary stores key-value pairs with fast lookup by key. Keys must be hashable (strings, numbers, tuples of those).

marks = {"Asha": 82, "Ravi": 74}
for name, score in marks.items():
    print(name, score)

print(marks.get("Meena", 0))   # 0 instead of a KeyError

8. What is a list comprehension?

A compact way to build a list from an iterable, optionally with a condition. Use it when the logic fits on one readable line.

squares_of_evens = [n * n for n in range(10) if n % 2 == 0]
print(squares_of_evens)   # [0, 4, 16, 36, 64]

9. What's the difference between a shallow copy and a deep copy?

A shallow copy creates a new outer container but shares the inner objects. A deep copy copies everything recursively.

import copy

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

grid[0][0] = 99
print(shallow[0][0])   # 99, the inner list is shared
print(deep[0][0])      # 1, fully independent

Functions and scope questions

10. What are *args and **kwargs?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.

def describe(*args, **kwargs):
    print(args, kwargs)

describe(1, 2, city="Anand")   # (1, 2) {'city': 'Anand'}

11. Why shouldn't you use a list as a default argument?

Default values are evaluated once, when the function is defined. A mutable default is shared between calls.

def add_item(item, basket=[]):      # bug
    basket.append(item)
    return basket

print(add_item("pen"))    # ['pen']
print(add_item("book"))   # ['pen', 'book'], surprise

def add_item_fixed(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

This is probably the single most common "gotcha" question for freshers.

12. What is a lambda function?

A small anonymous function written in one expression. It's most useful as a key for sorting.

students = [("Asha", 82), ("Ravi", 74), ("Meena", 91)]
students.sort(key=lambda s: s[1], reverse=True)
print(students[0])   # ('Meena', 91)

13. What is the LEGB rule?

It's the order Python searches for a name: Local, Enclosing function, Global (module), Built-in. If you assign to a name inside a function, Python treats it as local unless you declare it global or nonlocal.

14. How do you handle errors in Python?

With try / except, catching the specific exception you expect. else runs when no exception happened, and finally always runs.

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return None
    else:
        return round(result, 2)
    finally:
        pass   # cleanup would go here

print(safe_divide(10, 4))   # 2.5
print(safe_divide(10, 0))   # None

Catching a bare except: is a red flag in an interview, because it hides bugs.

OOP questions

15. What are classes and objects?

A class is a blueprint, and an object is an instance built from it. __init__ sets up the object's data, and self refers to the instance.

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.balance += amount

acc = Account("Asha")
acc.deposit(500)
print(acc.balance)   # 500

16. What is inheritance?

A child class reuses and extends a parent class. super() calls the parent's version of a method.

class SavingsAccount(Account):
    def __init__(self, owner, balance=0, rate=0.03):
        super().__init__(owner, balance)
        self.rate = rate

    def add_interest(self):
        self.balance += self.balance * self.rate

17. What's the difference between __str__ and __repr__?

__str__ is the readable version for users (print). __repr__ is the unambiguous version for developers, ideally something that could recreate the object. If you define only one, define __repr__.

PairFirst oneSecond one
list vs tupleMutable, use for collections that changeImmutable, can be a dict key
== vs isCompares valuesCompares identity (same object)
shallow vs deep copyNew outer object, shared inner objectsEverything copied recursively
append vs extendAdds one item (even a list)Adds each item of an iterable
remove vs popRemoves by valueRemoves by index and returns it
Quick answers to the comparisons interviewers ask most

Coding problems freshers get asked

18. Reverse a string and check for a palindrome

def is_palindrome(text):
    cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome("Madam"))                            # True
print(is_palindrome("A man, a plan, a canal: Panama"))   # True
print(is_palindrome("Python"))                           # False

Say why you cleaned the string: the interviewer wants to see you thought about case and punctuation.

19. Count how often each word appears

from collections import Counter

text = "the cat and the hat and the bat"
counts = Counter(text.split())
print(counts.most_common(2))   # [('the', 3), ('and', 2)]

If the interviewer says "without Counter", use a dictionary with get:

counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1

20. Find two numbers that add up to a target

The brute-force version checks every pair, which is O(n²). The better version uses a dictionary to remember what you've seen, which is O(n).

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 None

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

Explaining the trade-off out loud ("I'm using extra memory to get linear time") is worth as much as the code.

Practice questions: check yourself

Question 1Python · Mutability

What does this print? a = [1, 2]; b = a; b += [3]; print(a)

  1. A[1, 2]
  2. B[3]
  3. C[1, 2, 3]
  4. DAn error
Show answer and explanation

Correct answer: C

b = a makes both names point to one list, and += on a list extends it in place. So a shows [1, 2, 3]. With a tuple, += would create a new object instead.

Question 2Python · Functions

def f(x, items=[]): items.append(x); return items. What does f(1); print(f(2)) print?

  1. A[2]
  2. B[1, 2]
  3. C[1]
  4. DAn error
Show answer and explanation

Correct answer: B

The default list is created once and shared between calls, so the second call appends to the list that already holds 1. The fix is items=None and creating the list inside the function.

Question 3Python · Data structures

Which of these can be used as a dictionary key?

  1. A[1, 2]
  2. B{1, 2}
  3. C{"a": 1}
  4. D(1, 2)
Show answer and explanation

Correct answer: D

Keys must be hashable. Lists, sets and dictionaries are mutable and unhashable. A tuple of immutable values is hashable.

Question 4Python · Strings

What is the output of print("python"[::-2])?

  1. Anhy
  2. Bnohtyp
  3. Cpto
  4. Dyhn
Show answer and explanation

Correct answer: A

A step of -2 walks backwards from the last character, taking every second one: n (index 5), h (index 3), y (index 1).

How should a fresher prepare for a Python interview?

Reading answers feels productive, but it doesn't build the skill the coding round tests. Here's the plan I give students with two to three weeks:

  1. Week 1: Core types and mutability. Write small programs for each question above and predict the output before you run it.
  2. Week 2: Daily coding practice. Two or three short problems a day: strings, lists, dictionaries, counting, searching. Time yourself.
  3. Week 3: Mock rounds. Explain your solution out loud while you type, then improve it. That is exactly what the interview asks you to do.

For structured practice, Python interview practice has a bank of 200+ coding questions you solve in a browser editor (pandas and NumPy included), with hints, test checks and worked answers. It covers Python developer and data analyst tracks, and access is a one-time ₹199. If the role also asks for SQL, the SQL interview practice store has a free company set (ShopX) to start with, and other companies are ₹99 each or ₹699 for the bundle, with 30 days of access.

If you're still deciding which skills to build first, the data analyst roadmap for 2026 shows where Python fits next to Excel, SQL and Power BI.

FAQ

What Python questions are asked in a fresher interview?

Mostly core concepts: data types, lists vs tuples, dictionaries, mutability, == vs is, functions, *args and **kwargs, exception handling and basic OOP. Most rounds also include one or two short coding problems like reversing a string, counting words or two-sum.

How do I answer Python interview questions well?

Give a one-line definition, then a tiny example, then (if relevant) when you'd use it. Interviewers want to see that you understand the idea, not that you memorised a paragraph.

Is Python enough to get a job as a fresher?

Python plus one applied area usually is: web development (Django or FastAPI), data analysis (pandas and SQL), or automation and testing. Python alone, without projects, is a hard sell.

How long does it take to prepare for a Python interview?

If you already know the basics, two to four weeks of daily practice is a realistic window for fresher interviews. Most of that time should go into writing and running code.

Which Python version should I know for interviews in 2026?

Any recent Python 3 release is fine for interview questions. The concepts above (types, mutability, functions, OOP) have been stable across Python 3 versions.

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.