← Interview prep

Python interview questions

Python language, data structures, and common interview traps.

100 questions · Page 2 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 2 of 5

Questions 21–40 of 100 · 0 of 20 on this page marked learned

21.python-0021Easyfresher

Show the common ways to format strings in Python and when to use each.

f-strings (f'...{expr}...') are the modern default: readable, fast and able to embed expressions with format specs such as {price:.2f}. str.format is useful when the template is stored separately from the values. %-formatting is older but still used by the logging module, which formats lazily.

Full answer
python
name, price, qty = "Notebook", 45.5, 3
print(f"{name}: {qty} x {price:.2f} = {qty * price:,.2f}")
print(f"{name!r:>12}|{qty:03d}|{0.125:.1%}")
print(f"{qty=}, {price*qty=}")
template = "{item} costs {cost:.1f}"
print(template.format(item=name, cost=price))
print("%s costs %.1f" % (name, price))

Output:

text
Notebook: 3 x 45.50 = 136.50
  'Notebook'|003|12.5%
qty=3, price*qty=136.5
Notebook costs 45.5
Notebook costs 45.5

The format spec after the colon controls precision (.2f), thousands separators (,), padding and alignment (>12, 03d) and percentages (.1%). !r uses repr(), adding quotes. The = specifier, available since Python 3.8, prints the expression with its value, which is convenient for debugging. A stored template with named fields suits translations and configuration. For logging, pass values as arguments (log.info('%s costs %s', name, price)) so formatting only happens if the message is emitted.

python
name, price, qty = "Notebook", 45.5, 3
print(f"{name}: {qty} x {price:.2f} = {qty * price:,.2f}")
print(f"{name!r:>12}|{qty:03d}|{0.125:.1%}")
print(f"{qty=}, {price*qty=}")
template = "{item} costs {cost:.1f}"
print(template.format(item=name, cost=price))
print("%s costs %.1f" % (name, price))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • f-strings are the default
  • Format specs control precision and alignment
  • = helps debugging
  • str.format suits stored templates
  • logging uses lazy %-style

Common mistakes

  • Concatenating with + and str() everywhere
  • Formatting log messages eagerly with f-strings in hot paths

Follow-ups

  • How would you format a number in Indian lakh grouping?
  • What are template strings (t-strings) in Python 3.14?

Tips

  • Show one format spec
22.python-0022Easyfresher

How does slicing work on lists and strings, including negative steps?

seq[start:stop:step] returns a new sequence from start up to but not including stop, moving by step. Omitted bounds default to the ends, negative indexes count from the end, and a negative step walks backwards, so s[::-1] reverses. Slices never raise IndexError for out-of-range bounds.

Full answer
python
s = "PYTHON"
print(s[1:4], s[:2], s[-2:], s[::2], s[::-1])
nums = [0, 1, 2, 3, 4, 5]
print(nums[4:1:-1], nums[10:], nums[-100:2])
copy = nums[:]
copy[0] = 99
print(nums[0], copy[0])
nums[1:3] = ["a", "b", "c"]
print(nums)

Output:

text
YTH PY ON PTO NOHTYP
[4, 3, 2] [] [0, 1]
0 99
[0, 'a', 'b', 'c', 3, 4, 5]

s[1:4] gives 'YTH' because the stop index is excluded. s[::-1] reverses the string, and nums[4:1:-1] walks backwards from index 4 down to, but not including, index 1. Out-of-range bounds such as nums[10:] simply give an empty list. nums[:] makes a shallow copy, and assigning to a slice can replace a section with a different number of items, growing the list.

python
s = "PYTHON"
print(s[1:4], s[:2], s[-2:], s[::2], s[::-1])
nums = [0, 1, 2, 3, 4, 5]
print(nums[4:1:-1], nums[10:], nums[-100:2])
copy = nums[:]
copy[0] = 99
print(nums[0], copy[0])
nums[1:3] = ["a", "b", "c"]
print(nums)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • stop is exclusive
  • Negative indexes count from the end
  • Negative step reverses direction
  • Out-of-range slices do not raise
  • Slice assignment can resize lists

Common mistakes

  • Expecting the stop index to be included
  • Expecting IndexError from slices

Follow-ups

  • How does slice() as an object work?
  • Is s[::-1] the best way to reverse a list in place?

Tips

  • Count positions between characters
23.python-0023Easyfresher

What are the useful dictionary methods for safe lookups and updates?

d[key] raises KeyError when the key is missing, while d.get(key, default) returns a default. setdefault inserts a default if missing and returns the value, and the | operator (Python 3.9+) merges dicts into a new one, with the right side winning. Iterate with .items() to get keys and values together.

Full answer
python
stock = {"pen": 10, "ink": 0}
print(stock.get("pad"), stock.get("pad", 0))
try:
    stock["pad"]
except KeyError as e:
    print("KeyError:", e)
stock.setdefault("pad", 5)
stock.setdefault("pen", 99)
print(stock)
print(stock | {"pen": 12, "cap": 3})
for item, qty in stock.items():
    if qty == 0:
        print("out of stock:", item)
print(stock.pop("ink"), list(stock))

Output:

text
None 0
KeyError: 'pad'
{'pen': 10, 'ink': 0, 'pad': 5}
{'pen': 12, 'ink': 0, 'pad': 5, 'cap': 3}
out of stock: ink
0 ['pen', 'pad']

get returns None or the given default for 'pad' without raising. setdefault added 'pad' but left 'pen' unchanged because it already existed. The merge with | created a new dict where 'pen' took the right-hand value, while stock itself is unchanged until assigned (|= updates in place). pop removes a key and returns its value. Dicts keep insertion order, which the printed key list shows.

python
stock = {"pen": 10, "ink": 0}
print(stock.get("pad"), stock.get("pad", 0))
try:
    stock["pad"]
except KeyError as e:
    print("KeyError:", e)
stock.setdefault("pad", 5)
stock.setdefault("pen", 99)
print(stock)
print(stock | {"pen": 12, "cap": 3})
for item, qty in stock.items():
    if qty == 0:
        print("out of stock:", item)
print(stock.pop("ink"), list(stock))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • get avoids KeyError
  • setdefault inserts only if missing
  • | merges, right side wins
  • items() yields pairs
  • Dicts keep insertion order

Common mistakes

  • Checking 'if key in d' then indexing, twice the lookups
  • Modifying a dict while iterating over it

Follow-ups

  • When would defaultdict be better than setdefault?
  • What happens if a dict changes size during iteration?

Tips

  • Show a missing key both ways
24.python-0024Easyfresher

How do enumerate and zip make loops cleaner, and what does zip do with unequal lengths?

enumerate(iterable, start) yields (index, item) pairs, replacing manual counters and range(len(...)). zip pairs items from several iterables and stops at the shortest; zip(..., strict=True) raises a ValueError on unequal lengths, and itertools.zip_longest pads the shorter ones.

Full answer
python
from itertools import zip_longest
names = ["Asha", "Ben", "Chen"]
marks = [88, 75]
for rank, name in enumerate(names, start=1):
    print(rank, name)
print(list(zip(names, marks)))
print(list(zip_longest(names, marks, fillvalue=None)))
try:
    list(zip(names, marks, strict=True))
except ValueError as e:
    print("ValueError:", e)
print(dict(zip(names, marks)))

Output:

text
1 Asha
2 Ben
3 Chen
[('Asha', 88), ('Ben', 75)]
[('Asha', 88), ('Ben', 75), ('Chen', None)]
ValueError: zip() argument 2 is shorter than argument 1
{'Asha': 88, 'Ben': 75}

Starting enumerate at 1 gives human-friendly ranks. Plain zip silently dropped Chen because only two marks exist, which can hide data bugs; strict=True (Python 3.10+) turns that into an error, and zip_longest keeps Chen with None. dict(zip(keys, values)) is a common way to build a mapping. Both functions return lazy iterators, so wrap them in list() to see or reuse the results.

python
from itertools import zip_longest
names = ["Asha", "Ben", "Chen"]
marks = [88, 75]
for rank, name in enumerate(names, start=1):
    print(rank, name)
print(list(zip(names, marks)))
print(list(zip_longest(names, marks, fillvalue=None)))
try:
    list(zip(names, marks, strict=True))
except ValueError as e:
    print("ValueError:", e)
print(dict(zip(names, marks)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • enumerate replaces manual counters
  • zip stops at the shortest
  • strict=True catches unequal lengths
  • zip_longest pads
  • Both are lazy iterators

Common mistakes

  • Using range(len(x)) to loop
  • Losing data silently with zip

Follow-ups

  • How would you unzip a list of pairs?
  • How do you loop over two lists in parallel with indexes?

Tips

  • Mention strict=True
25.python-0025Easyfresher

What values are falsy in Python, and why does 'if items:' work for empty lists?

False, None, zero of any numeric type, and empty containers or strings are falsy; everything else is truthy by default. if items: is the idiomatic emptiness check because an empty list is falsy. Classes control truthiness with __bool__ or, failing that, __len__.

Full answer
python
values = [0, 0.0, "", [], {}, set(), None, False, "0", [0], " ", 0.1]
print([v for v in values if not v])
print([v for v in values if v])

class Basket:
    def __init__(self, items): self.items = items
    def __len__(self): return len(self.items)
print(bool(Basket([])), bool(Basket(["pen"])))

count = 0
print(count or "no value", count if count is not None else "no value")

Output:

text
[0, 0.0, '', [], {}, set(), None, False]
['0', [0], ' ', 0.1]
False True
no value 0

The string '0', the list [0] and a space are truthy because they are non-empty, which trips up people coming from other languages. Basket has no __bool__, so Python uses __len__. The last line shows a classic bug: count or 'no value' replaces a legitimate 0 with the fallback, while an explicit is not None test keeps it. Use plain truthiness for 'is it empty', and explicit comparisons when zero or empty strings are valid values.

python
values = [0, 0.0, "", [], {}, set(), None, False, "0", [0], " ", 0.1]
print([v for v in values if not v])
print([v for v in values if v])

class Basket:
    def __init__(self, items): self.items = items
    def __len__(self): return len(self.items)
print(bool(Basket([])), bool(Basket(["pen"])))

count = 0
print(count or "no value", count if count is not None else "no value")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Zero, empty containers, None and False are falsy
  • Non-empty strings like '0' are truthy
  • __bool__ or __len__ define truthiness
  • x or default replaces valid zeros

Common mistakes

  • Using or for defaults when 0 is valid
  • Writing if len(items) == 0

Follow-ups

  • How does numpy handle truthiness of arrays?
  • What does the walrus operator add to conditions?

Tips

  • List the falsy values
26.python-0026Easyfresher

How does Python's scope rule (LEGB) work, and when do you need global or nonlocal?

Names are looked up in Local, Enclosing function, Global (module) and Built-in scopes, in that order. Assigning to a name inside a function makes it local for the whole function, so reading it before assignment raises UnboundLocalError. global and nonlocal declare that assignment should target the module or enclosing function scope instead.

Full answer
python
x = "global"
def outer():
    x = "enclosing"
    def inner():
        return x
    return inner()
print(outer())

counter = 0
def bump_bad():
    try:
        counter += 1
    except UnboundLocalError as e:
        print("UnboundLocalError:", e)
bump_bad()

def make_counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step
c = make_counter()
print(c(), c(), c())

Output:

text
enclosing
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
1 2 3

inner finds x in the enclosing function before the global one. In bump_bad, counter += 1 is an assignment, so counter is local throughout the function and reading it first fails; the message in Python 3.13 names the variable. nonlocal n lets step rebind the enclosing variable, giving a counter that remembers its state. Prefer returning values or using objects over global, which makes code harder to test.

python
x = "global"
def outer():
    x = "enclosing"
    def inner():
        return x
    return inner()
print(outer())

counter = 0
def bump_bad():
    try:
        counter += 1
    except UnboundLocalError as e:
        print("UnboundLocalError:", e)
bump_bad()

def make_counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step
c = make_counter()
print(c(), c(), c())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Lookup order: local, enclosing, global, built-in
  • Assignment makes a name local
  • UnboundLocalError from reading before assigning
  • nonlocal rebinds enclosing names
  • Avoid global state

Common mistakes

  • Shadowing built-ins like list or id
  • Using global to share state between functions

Follow-ups

  • What does a closure capture?
  • Why does shadowing list cause errors later?

Tips

  • Explain why counter is local
27.python-0027Easyfresher

Read a text file safely and count word frequencies.

Open files with a with statement so they close automatically, specify encoding='utf-8', and iterate line by line for large files. collections.Counter counts words directly, and pathlib.Path offers convenient read_text and write_text for small files.

Full answer
python
import tempfile
from collections import Counter
from pathlib import Path

path = Path(tempfile.mkdtemp()) / "notes.txt"
path.write_text("Pune rain. Pune traffic!\nrain again\n", encoding="utf-8")

counts = Counter()
with path.open(encoding="utf-8") as f:
    for line in f:
        words = [w.strip(".,!?").lower() for w in line.split()]
        counts.update(words)
print(counts.most_common(2))
print(path.read_text(encoding="utf-8").count("\n"), path.exists())

Output:

text
[('pune', 2), ('rain', 2)]
2 True

The file is written and read with an explicit encoding, since the default depends on the platform. Reading line by line keeps memory use flat for big files. Stripping punctuation and lowercasing makes 'Pune' and 'rain.' count with their other occurrences, so both appear twice. Without with, an exception between open and close would leave the file open. For CSV or JSON, use the csv and json modules instead of splitting text by hand.

python
import tempfile
from collections import Counter
from pathlib import Path

path = Path(tempfile.mkdtemp()) / "notes.txt"
path.write_text("Pune rain. Pune traffic!\nrain again\n", encoding="utf-8")

counts = Counter()
with path.open(encoding="utf-8") as f:
    for line in f:
        words = [w.strip(".,!?").lower() for w in line.split()]
        counts.update(words)
print(counts.most_common(2))
print(path.read_text(encoding="utf-8").count("\n"), path.exists())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Use with to close files
  • Pass encoding explicitly
  • Iterate lines for large files
  • Counter counts and ranks
  • pathlib simplifies paths and small reads

Common mistakes

  • Forgetting encoding and breaking on Windows
  • Reading huge files with read() into memory

Follow-ups

  • How would you process a 10 GB log file?
  • How do you write a file atomically?

Tips

  • Mention encoding
28.python-0028Easyfresher

How do sorted() and list.sort() differ, and how do you sort by several keys?

sorted() returns a new list from any iterable, while list.sort() sorts a list in place and returns None. Both take key and reverse. Sorting is stable, so you can sort by several keys with a tuple key, or by sorting in passes from the least to the most important key.

Full answer
python
students = [("Asha", "B", 88), ("Ben", "A", 75), ("Chen", "B", 92), ("Dara", "A", 75)]
by_marks = sorted(students, key=lambda s: s[2], reverse=True)
print(by_marks)
print(sorted(students, key=lambda s: (s[1], -s[2])))
result = students.sort(key=lambda s: s[0])
print(result, students[0])
print(sorted(["banana", "apple", "Cherry"]), sorted(["banana", "apple", "Cherry"], key=str.lower))

Output:

text
[('Chen', 'B', 92), ('Asha', 'B', 88), ('Ben', 'A', 75), ('Dara', 'A', 75)]
[('Ben', 'A', 75), ('Dara', 'A', 75), ('Chen', 'B', 92), ('Asha', 'B', 88)]
None ('Asha', 'B', 88)
['Cherry', 'apple', 'banana'] ['apple', 'banana', 'Cherry']

Ben and Dara both have 75, and they keep their original order in by_marks because the sort is stable. The tuple key sorts by section and then by marks descending, using the minus sign for the numeric part. list.sort() returns None, so assigning its result is a common bug. Plain string sorting puts 'Cherry' first because uppercase letters sort before lowercase; key=str.lower gives the case-insensitive order apple, banana, Cherry.

python
students = [("Asha", "B", 88), ("Ben", "A", 75), ("Chen", "B", 92), ("Dara", "A", 75)]
by_marks = sorted(students, key=lambda s: s[2], reverse=True)
print(by_marks)
print(sorted(students, key=lambda s: (s[1], -s[2])))
result = students.sort(key=lambda s: s[0])
print(result, students[0])
print(sorted(["banana", "apple", "Cherry"]), sorted(["banana", "apple", "Cherry"], key=str.lower))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • sorted returns a new list; sort works in place
  • key functions define the order
  • Sorting is stable
  • Tuple keys sort by several fields
  • Uppercase sorts before lowercase

Common mistakes

  • Writing x = x.sort()
  • Using cmp-style functions without functools.cmp_to_key

Follow-ups

  • How would you sort descending by a string field and ascending by a number?
  • What algorithm does Python use?

Tips

  • Mention stability
29.python-0029Easyfresher

How do you define a custom exception and raise it with useful context?

Subclass Exception (or a more specific built-in), optionally add attributes, and raise it with a clear message. Use raise NewError(...) from err to chain the original cause, which keeps the full traceback for debugging. Catch your own exception type at the boundary where you can handle it.

Full answer
python
class InsufficientStock(Exception):
    def __init__(self, item, wanted, available):
        super().__init__(f"{item}: wanted {wanted}, only {available} left")
        self.item, self.wanted, self.available = item, wanted, available

def reserve(stock, item, qty):
    try:
        available = stock[item]
    except KeyError as err:
        raise LookupError(f"unknown item {item!r}") from err
    if qty > available:
        raise InsufficientStock(item, qty, available)
    stock[item] -= qty

stock = {"pen": 2}
for item, qty in [("pen", 5), ("lamp", 1)]:
    try:
        reserve(stock, item, qty)
    except InsufficientStock as e:
        print("handled:", e, "| available =", e.available)
    except LookupError as e:
        print("handled:", e, "| cause:", type(e.__cause__).__name__)

Output:

text
handled: pen: wanted 5, only 2 left | available = 2
handled: unknown item 'lamp' | cause: KeyError

InsufficientStock carries structured data, so callers can react to e.available instead of parsing the message. For an unknown item, the KeyError is translated into a LookupError with a clearer message, and from err stores the original in __cause__, so a traceback would show both. Name exceptions after the problem, keep a small hierarchy for a library (one base class plus specific subclasses), and avoid catching broad Exception unless you re-raise or log it.

python
class InsufficientStock(Exception):
    def __init__(self, item, wanted, available):
        super().__init__(f"{item}: wanted {wanted}, only {available} left")
        self.item, self.wanted, self.available = item, wanted, available

def reserve(stock, item, qty):
    try:
        available = stock[item]
    except KeyError as err:
        raise LookupError(f"unknown item {item!r}") from err
    if qty > available:
        raise InsufficientStock(item, qty, available)
    stock[item] -= qty

stock = {"pen": 2}
for item, qty in [("pen", 5), ("lamp", 1)]:
    try:
        reserve(stock, item, qty)
    except InsufficientStock as e:
        print("handled:", e, "| available =", e.available)
    except LookupError as e:
        print("handled:", e, "| cause:", type(e.__cause__).__name__)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Subclass Exception
  • Add attributes for structured data
  • raise ... from keeps the cause
  • Catch specific types where you can handle them
  • One base class per library

Common mistakes

  • Raising bare Exception with a string
  • Swallowing the original error

Follow-ups

  • What does raise ... from None do?
  • How do exception notes (add_note) help?

Tips

  • Show __cause__
30.python-0030Easyfresher

Explain class basics: attributes, methods, class attributes and self.

A class bundles data (attributes) and behaviour (methods). Instance attributes are set on self, usually in __init__, and belong to each object; class attributes are shared by all instances. Methods receive the instance as self automatically when called on an object.

Full answer
python
class Account:
    bank = "Schoolabe Bank"
    count = 0

    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        Account.count += 1

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

a, b = Account("Asha"), Account("Ben", 100)
print(a.deposit(50), b.balance, Account.count, a.bank)
b.bank = "Other"
print(a.bank, b.bank, Account.bank)
print(Account.deposit(a, 10))

Output:

text
50 100 2 Schoolabe Bank
Schoolabe Bank Other Schoolabe Bank
60

Each account keeps its own owner and balance, while count lives on the class and tracks how many accounts exist. Assigning b.bank creates an instance attribute that hides the class attribute for b only; a and the class still see the original. The last line shows what a.deposit(10) really does: it calls the function on the class with a as self. Mutable class attributes, such as a shared list, are a common source of bugs because every instance modifies the same object.

python
class Account:
    bank = "Schoolabe Bank"
    count = 0

    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        Account.count += 1

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

a, b = Account("Asha"), Account("Ben", 100)
print(a.deposit(50), b.balance, Account.count, a.bank)
b.bank = "Other"
print(a.bank, b.bank, Account.bank)
print(Account.deposit(a, 10))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Instance attributes live on self
  • Class attributes are shared
  • Assigning on an instance shadows the class attribute
  • Methods get self automatically
  • Avoid mutable class attributes

Common mistakes

  • Putting a list as a class attribute for per-instance data
  • Forgetting self in method signatures

Follow-ups

  • What are classmethod and staticmethod for?
  • When would you use a dataclass instead?

Tips

  • Show shadowing of a class attribute
31.python-0031Easyfresher

How does inheritance work, and what does super() do?

A subclass inherits attributes and methods from its parent and can override them. super() calls the next class in the method resolution order, typically to run the parent's __init__ or extend a method rather than replace it. isinstance checks respect inheritance.

Full answer
python
class Employee:
    def __init__(self, name, salary):
        self.name, self.salary = name, salary
    def annual_pay(self):
        return self.salary * 12
    def describe(self):
        return f"{self.name} earns {self.annual_pay():,}"

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self.bonus = bonus
    def annual_pay(self):
        return super().annual_pay() + self.bonus

staff = [Employee("Tom", 50_000), Manager("Asha", 90_000, 200_000)]
for s in staff:
    print(s.describe(), isinstance(s, Employee), type(s).__name__)
print(Manager.__mro__)

Output:

text
Tom earns 600,000 True Employee
Asha earns 1,280,000 True Manager
(<class '__main__.Manager'>, <class '__main__.Employee'>, <class 'object'>)

Manager.__init__ reuses the parent's setup through super() and adds bonus. annual_pay extends the parent's calculation instead of copying it. describe is defined only on Employee, yet for Asha it calls the overridden annual_pay, which is polymorphism. __mro__ shows the lookup order Python uses: Manager, Employee, object. Prefer composition when the relationship is 'has a' rather than 'is a', and keep hierarchies shallow so behaviour stays easy to trace.

python
class Employee:
    def __init__(self, name, salary):
        self.name, self.salary = name, salary
    def annual_pay(self):
        return self.salary * 12
    def describe(self):
        return f"{self.name} earns {self.annual_pay():,}"

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self.bonus = bonus
    def annual_pay(self):
        return super().annual_pay() + self.bonus

staff = [Employee("Tom", 50_000), Manager("Asha", 90_000, 200_000)]
for s in staff:
    print(s.describe(), isinstance(s, Employee), type(s).__name__)
print(Manager.__mro__)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Subclasses inherit and override
  • super() calls the next class in the MRO
  • Overrides are used by inherited methods
  • isinstance respects inheritance
  • Prefer composition for has-a

Common mistakes

  • Copying parent code instead of calling super()
  • Deep inheritance hierarchies

Follow-ups

  • How does the MRO work with multiple inheritance?
  • When would you choose composition?

Tips

  • Show super() in __init__
32.python-0032Easyfresher

How do set operations work, and when are sets the right tool?

Sets store unique hashable items with fast membership tests. Union (|), intersection (&), difference (-) and symmetric difference (^) compare collections directly. Use sets to deduplicate, to find common or missing items, and for fast 'in' checks; they do not keep order.

Full answer
python
python_students = {"Asha", "Ben", "Chen"}
sql_students = {"Ben", "Dara", "Chen"}
print(sorted(python_students | sql_students))
print(sorted(python_students & sql_students))
print(sorted(python_students - sql_students))
print(sorted(python_students ^ sql_students))
print("Ben" in sql_students, {"Ben"} <= python_students)
tags = ["sql", "python", "sql"]
print(len(set(tags)), list(dict.fromkeys(tags)))

Output:

text
['Asha', 'Ben', 'Chen', 'Dara']
['Ben', 'Chen']
['Asha']
['Asha', 'Dara']
True True
2 ['sql', 'python']

Results are wrapped in sorted() because set order varies between runs, which matters in tests and examples. Intersection shows who takes both courses; difference shows who takes Python only; symmetric difference shows people in exactly one. <= tests for a subset. set(tags) removes duplicates but loses order, while dict.fromkeys keeps the first-seen order. Only hashable items such as strings, numbers and tuples can be set members.

python
python_students = {"Asha", "Ben", "Chen"}
sql_students = {"Ben", "Dara", "Chen"}
print(sorted(python_students | sql_students))
print(sorted(python_students & sql_students))
print(sorted(python_students - sql_students))
print(sorted(python_students ^ sql_students))
print("Ben" in sql_students, {"Ben"} <= python_students)
tags = ["sql", "python", "sql"]
print(len(set(tags)), list(dict.fromkeys(tags)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Sets hold unique hashable items
  • | & - ^ compare collections
  • Membership is fast
  • Order is not preserved
  • dict.fromkeys deduplicates in order

Common mistakes

  • Relying on set iteration order
  • Trying to put lists into sets

Follow-ups

  • What is a frozenset for?
  • How would you find duplicates in a list?

Tips

  • Sort sets before printing
33.python-0033Easyfresher

Why does 0.1 + 0.2 == 0.3 evaluate to False, and how should money be handled?

Floats are binary fractions, and 0.1 and 0.2 cannot be represented exactly, so their sum is 0.30000000000000004. Compare floats with math.isclose, and use decimal.Decimal (built from strings) or integer paise for money. round() uses banker's rounding on exact halves.

Full answer
python
import math
from decimal import Decimal, ROUND_HALF_UP
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"), Decimal(0.1))
print(round(2.5), round(3.5), round(2.675, 2))
print(Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
price_paise = 4550
print(price_paise * 3 / 100)

Output:

text
0.30000000000000004 False True
0.3 0.1000000000000000055511151231257827021181583404541015625
2 4 2.67
2.68
136.5

Decimal('0.1') is exact, while Decimal(0.1) reveals the float's real binary value, which is why Decimals should be built from strings. round(2.5) gives 2 and round(3.5) gives 4: Python rounds exact halves to the even neighbour. round(2.675, 2) gives 2.67 because the float is slightly below 2.675. For invoices, use Decimal with an explicit rounding mode or keep amounts in integer paise and format only for display.

python
import math
from decimal import Decimal, ROUND_HALF_UP
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"), Decimal(0.1))
print(round(2.5), round(3.5), round(2.675, 2))
print(Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
price_paise = 4550
print(price_paise * 3 / 100)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Floats are binary approximations
  • Use math.isclose to compare
  • Build Decimal from strings
  • round uses banker's rounding
  • Store money as Decimal or integer minor units

Common mistakes

  • Comparing floats with ==
  • Constructing Decimal from a float

Follow-ups

  • What is the decimal context?
  • How does rounding work for negative numbers?

Tips

  • Show the exact sum
34.python-0034Easyfresher

What do type hints do at runtime, and how are they checked?

Type hints document expected types and let tools such as mypy, pyright and IDEs catch errors before running the code. Python does not enforce them at runtime: a function annotated to take int happily receives a string. Libraries such as Pydantic read the annotations to validate data explicitly.

Full answer
python
def total(prices: list[float], tax: float = 0.18) -> float:
    return round(sum(prices) * (1 + tax), 2)

print(total([100.0, 50.0]))
print(total.__annotations__)
try:
    print(total(["100"]))
except TypeError as e:
    print("TypeError at runtime:", e)

from typing import TypedDict
class User(TypedDict):
    name: str
    age: int
u: User = {"name": "Asha", "age": "twenty"}
print(u)

Output:

text
177.0
{'prices': list[float], 'tax': <class 'float'>, 'return': <class 'float'>}
TypeError at runtime: unsupported operand type(s) for +: 'int' and 'str'
{'name': 'Asha', 'age': 'twenty'}

Annotations are stored in __annotations__ and otherwise ignored when the code runs. Passing a list of strings fails only because sum cannot add strings, not because of the hint. The TypedDict with a wrong age type is accepted at runtime; a type checker would report it. Modern syntax uses built-in generics such as list[float] and unions like int | None. Adding hints to function signatures first gives most of the benefit in a codebase.

python
def total(prices: list[float], tax: float = 0.18) -> float:
    return round(sum(prices) * (1 + tax), 2)

print(total([100.0, 50.0]))
print(total.__annotations__)
try:
    print(total(["100"]))
except TypeError as e:
    print("TypeError at runtime:", e)

from typing import TypedDict
class User(TypedDict):
    name: str
    age: int
u: User = {"name": "Asha", "age": "twenty"}
print(u)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Hints are not enforced at runtime
  • Type checkers use them statically
  • Stored in __annotations__
  • Use list[int] and X | None syntax
  • Pydantic validates explicitly

Common mistakes

  • Expecting hints to reject wrong types
  • Over-annotating local variables

Follow-ups

  • What is the difference between mypy and Pydantic validation?
  • What are Protocols?

Tips

  • Separate static checking from runtime
35.python-0035Easyfresher

Convert between JSON text and Python objects, and handle types JSON does not support.

json.dumps turns dicts, lists, strings, numbers, booleans and None into JSON text, and json.loads parses it back. Types like datetime, Decimal and sets are not supported directly; pass default=... to convert them, or convert before dumping. Tuples become lists and dict keys become strings.

Full answer
python
import json
from datetime import date
from decimal import Decimal
order = {"id": 7, "items": ("pen", "ink"), "paid": True, "note": None, 1: "x"}
text = json.dumps(order)
print(text)
print(json.loads(text))
data = {"day": date(2026, 12, 4), "amount": Decimal("45.50")}
try:
    json.dumps(data)
except TypeError as e:
    print("TypeError:", e)
print(json.dumps(data, default=str))
print(json.dumps({"name": "Asha", "city": "पुणे"}, ensure_ascii=False))

Output:

text
{"id": 7, "items": ["pen", "ink"], "paid": true, "note": null, "1": "x"}
{'id': 7, 'items': ['pen', 'ink'], 'paid': True, 'note': None, '1': 'x'}
TypeError: Object of type date is not JSON serializable
{"day": "2026-12-04", "amount": "45.50"}
{"name": "Asha", "city": "पुणे"}

The tuple came back as a list, None became null and back, and the integer key 1 became the string '1', so a round trip does not always return the same object. default=str converts unsupported values to text, which suits dates and Decimals in logs; for APIs, prefer explicit formats such as ISO dates. ensure_ascii=False keeps non-ASCII text readable instead of \u escapes.

python
import json
from datetime import date
from decimal import Decimal
order = {"id": 7, "items": ("pen", "ink"), "paid": True, "note": None, 1: "x"}
text = json.dumps(order)
print(text)
print(json.loads(text))
data = {"day": date(2026, 12, 4), "amount": Decimal("45.50")}
try:
    json.dumps(data)
except TypeError as e:
    print("TypeError:", e)
print(json.dumps(data, default=str))
print(json.dumps({"name": "Asha", "city": "पुणे"}, ensure_ascii=False))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • dumps and loads convert both ways
  • Tuples become lists; keys become strings
  • default handles unsupported types
  • ensure_ascii=False keeps Unicode readable

Common mistakes

  • Expecting exact round trips
  • Sending Decimal or datetime without converting

Follow-ups

  • How would you parse ISO dates back into datetime?
  • When would you use Pydantic for JSON?

Tips

  • Show what changes in a round trip
36.python-0036Easyfresher

What are the most useful string methods for cleaning user input?

strip removes surrounding whitespace, lower or casefold normalise case, replace and split reshape text, startswith and endswith test prefixes, and isdigit or isalpha check content. Strings are immutable, so every method returns a new string that must be assigned.

Full answer
python
raw = "  ASHA.Rao@Example.COM  "
email = raw.strip().lower()
print(repr(email), email.endswith("@example.com"))
name = "  asha   rao "
print(" ".join(name.split()).title())
phone = "98-765 43210"
digits = phone.replace("-", "").replace(" ", "")
print(digits, digits.isdigit(), len(digits) == 10)
print("Straße".lower(), "Straße".casefold())
s = "pen"
s.upper()
print(s)

Output:

text
'asha.rao@example.com' True
Asha Rao
9876543210 True True
straße strasse
pen

strip().lower() gives a clean, comparable email. ' '.join(name.split()) collapses runs of spaces, and title() capitalises each word. Removing separators before isdigit() checks a phone number. casefold() is stronger than lower() for case-insensitive comparison of international text, turning 'ß' into 'ss'. The last lines show immutability: s.upper() returned a new string that was thrown away, so s is still 'pen'.

python
raw = "  ASHA.Rao@Example.COM  "
email = raw.strip().lower()
print(repr(email), email.endswith("@example.com"))
name = "  asha   rao "
print(" ".join(name.split()).title())
phone = "98-765 43210"
digits = phone.replace("-", "").replace(" ", "")
print(digits, digits.isdigit(), len(digits) == 10)
print("Straße".lower(), "Straße".casefold())
s = "pen"
s.upper()
print(s)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • strip, lower, split and join cover most cleaning
  • casefold for international comparisons
  • isdigit checks content
  • Strings are immutable
  • Assign method results

Common mistakes

  • Calling a string method without using the result
  • Using lower() for Unicode-insensitive matching

Follow-ups

  • How would you validate an email properly?
  • When would you use regular expressions instead?

Tips

  • Show immutability
37.python-0037Easyfresher

Write a function that returns the second largest distinct number in a list.

Remove duplicates with a set, then take the second largest, handling lists with fewer than two distinct values explicitly. A single pass tracking the largest and second largest avoids sorting and works in O(n) time.

Full answer
python
def second_largest(nums):
    first = second = None
    for n in nums:
        if first is None or n > first:
            first, second = n, first
        elif n != first and (second is None or n > second):
            second = n
    return second

for case in ([4, 9, 2, 9, 7], [5, 5], [], [3], [-1, -5, -3]):
    print(case, "->", second_largest(case))

print(sorted(set([4, 9, 2, 9, 7]))[-2])

Output:

text
[4, 9, 2, 9, 7] -> 7
[5, 5] -> None
[] -> None
[3] -> None
[-1, -5, -3] -> -3
7

The loop keeps two values. A new maximum pushes the old one into second place; a value equal to the maximum is skipped, so duplicates of 9 do not count twice. Lists without two distinct values return None, which the caller must handle, rather than raising an IndexError deep inside. The one-line sorted(set(...))[-2] is fine for small inputs but sorts in O(n log n) and fails on short lists. Interviewers usually want the edge cases discussed: duplicates, negatives, empty input.

python
def second_largest(nums):
    first = second = None
    for n in nums:
        if first is None or n > first:
            first, second = n, first
        elif n != first and (second is None or n > second):
            second = n
    return second

for case in ([4, 9, 2, 9, 7], [5, 5], [], [3], [-1, -5, -3]):
    print(case, "->", second_largest(case))

print(sorted(set([4, 9, 2, 9, 7]))[-2])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Track largest and second largest in one pass
  • Skip values equal to the largest
  • Return None for fewer than two distinct values
  • sorted(set()) works for small inputs

Common mistakes

  • Returning the max again when it is duplicated
  • Crashing on short lists

Follow-ups

  • How would you find the k-th largest?
  • What does heapq.nlargest do?

Tips

  • List edge cases first
38.python-0038Easyfresher

How do you check whether a string is a palindrome, ignoring case and punctuation?

Normalise the string by keeping only letters and digits in lowercase, then compare it with its reverse. A two-pointer loop that skips non-alphanumeric characters does the same in O(1) extra space.

Full answer
python
def is_palindrome(s):
    cleaned = [c.casefold() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

def is_palindrome_two_pointers(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].casefold() != s[j].casefold():
            return False
        else:
            i, j = i + 1, j - 1
    return True

for text in ["Never odd or even", "A man, a plan, a canal: Panama!", "Python", ""]:
    print(repr(text), is_palindrome(text), is_palindrome_two_pointers(text))

Output:

text
'Never odd or even' True True
'A man, a plan, a canal: Panama!' True True
'Python' False False
'' True True

Both versions agree on every case. The first builds a cleaned list and compares it with its reverse, which is short and clear but uses extra memory. The second walks inward from both ends, skipping punctuation and spaces, and stops at the first mismatch. An empty string counts as a palindrome, an edge case worth stating. isalnum accepts letters and digits from any script, so the functions also work for non-English text.

python
def is_palindrome(s):
    cleaned = [c.casefold() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

def is_palindrome_two_pointers(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].casefold() != s[j].casefold():
            return False
        else:
            i, j = i + 1, j - 1
    return True

for text in ["Never odd or even", "A man, a plan, a canal: Panama!", "Python", ""]:
    print(repr(text), is_palindrome(text), is_palindrome_two_pointers(text))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Normalise case and drop non-alphanumerics
  • Compare with the reverse
  • Two pointers use constant extra space
  • State edge cases such as empty strings

Common mistakes

  • Forgetting punctuation and spaces
  • Using lower() where casefold is safer

Follow-ups

  • How would you find the longest palindromic substring?
  • What is the time complexity of each version?

Tips

  • Offer both versions
39.python-0039Easyfresher

What does range() return, and why is 'for i in range(len(items))' often a code smell?

range returns a lazy, immutable sequence of integers that supports len, indexing and fast membership without storing every number. Looping with range(len(items)) only to index items is usually clearer as for item in items, or for i, item in enumerate(items) when the index is needed.

Full answer
python
r = range(0, 20, 5)
print(r, list(r), len(r), r[2], 15 in r, 7 in r)
import sys
print(sys.getsizeof(range(10**9)) < 100)
items = ["pen", "ink", "pad"]
for i in range(len(items)):
    print(i, items[i])
for i, item in enumerate(items):
    print(i, item)
print(list(range(5, 0, -2)))

Output:

text
range(0, 20, 5) [0, 5, 10, 15] 4 10 True False
True
0 pen
1 ink
2 pad
0 pen
1 ink
2 pad
[5, 3, 1]

A range of a billion numbers takes only a few dozen bytes because values are computed on demand, and 15 in r is answered arithmetically rather than by scanning. The two loops print the same thing, but the enumerate version avoids repeated indexing and works with any iterable, not only sequences. Negative steps count down, and the stop value is excluded as in slicing. Use range(len(...)) when you truly need to modify items by position or compare neighbours.

python
r = range(0, 20, 5)
print(r, list(r), len(r), r[2], 15 in r, 7 in r)
import sys
print(sys.getsizeof(range(10**9)) < 100)
items = ["pen", "ink", "pad"]
for i in range(len(items)):
    print(i, items[i])
for i, item in enumerate(items):
    print(i, item)
print(list(range(5, 0, -2)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • range is lazy and constant-size
  • Supports len, indexing and fast membership
  • Prefer direct iteration or enumerate
  • Stop is exclusive
  • Negative steps count down

Common mistakes

  • Indexing in loops unnecessarily
  • Calling list(range(...)) for large ranges

Follow-ups

  • How do you loop over adjacent pairs?
  • How would you iterate backwards?

Tips

  • Show enumerate as the alternative
40.python-0040Mediummid

What do dataclasses generate for you, and how do you handle mutable defaults and immutability?

@dataclass generates __init__, __repr__ and __eq__ from annotated fields, and optionally ordering, hashing and __slots__. Mutable defaults need field(default_factory=list). frozen=True makes instances immutable and hashable, which suits value objects such as money or coordinates.

Full answer
python
from dataclasses import dataclass, field, asdict, replace

@dataclass
class Order:
    id: int
    items: list[str] = field(default_factory=list)
    paid: bool = False

@dataclass(frozen=True, order=True)
class Money:
    amount_paise: int
    currency: str = "INR"

o = Order(1); o.items.append("pen")
print(o, Order(2).items, o == Order(1, ["pen"]))
m = Money(4550)
try:
    m.amount_paise = 1
except Exception as e:
    print(type(e).__name__)
print(replace(m, amount_paise=100), sorted([Money(300), Money(100)])[0], {m: "ok"}[Money(4550)])
print(asdict(o))

Output:

text
Order(id=1, items=['pen'], paid=False) [] True
FrozenInstanceError
Money(amount_paise=100, currency='INR') Money(amount_paise=100, currency='INR') ok
{'id': 1, 'items': ['pen'], 'paid': False}

Each Order gets its own list because default_factory runs per instance; writing items: list = [] raises a ValueError at class creation, which protects against the shared-default bug. The frozen Money rejects assignment with FrozenInstanceError, can be a dict key, and order=True adds comparisons field by field. replace creates a modified copy, the usual way to 'change' a frozen object, and asdict converts to plain dicts for JSON. Add slots=True (Python 3.10+) to save memory for many instances.

python
from dataclasses import dataclass, field, asdict, replace

@dataclass
class Order:
    id: int
    items: list[str] = field(default_factory=list)
    paid: bool = False

@dataclass(frozen=True, order=True)
class Money:
    amount_paise: int
    currency: str = "INR"

o = Order(1); o.items.append("pen")
print(o, Order(2).items, o == Order(1, ["pen"]))
m = Money(4550)
try:
    m.amount_paise = 1
except Exception as e:
    print(type(e).__name__)
print(replace(m, amount_paise=100), sorted([Money(300), Money(100)])[0], {m: "ok"}[Money(4550)])
print(asdict(o))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Generates __init__, __repr__, __eq__
  • default_factory for mutable defaults
  • frozen=True for value objects
  • replace makes modified copies
  • slots=True saves memory

Common mistakes

  • Using a mutable default directly
  • Mutating frozen instances through nested lists

Follow-ups

  • How does a dataclass compare with Pydantic models?
  • What does __post_init__ do?

Tips

  • Mention default_factory