Python Interview Questions for Freshers (2026): 20 Answers with Code Examples

Share this article

Updated: 26 October 2026. A practical Hiring365 guide for students and fresh graduates in India.

Who should use this Python interview guide?

Python appears in software development, automation, data analysis and testing. Interviews differ by role: a developer may need algorithmic problem solving, whereas a data analyst may discuss pandas and datasets. The following 20 questions are practice examples, not leaked or guaranteed questions from any employer.

Python basics: questions 1–6

  1. What is Python? A high-level, general-purpose language with dynamic typing and a large standard library.
  2. List vs tuple? Lists are mutable; tuples are immutable containers. Both preserve order.
  3. What is a dictionary? A mapping of hashable keys to values; typical lookup is efficient, but never assume sorted keys.
  4. What is a set? An unordered collection of unique hashable elements, useful for membership tests and deduplication.
  5. What is the difference between == and is? == compares equality, while is tests object identity. Use is None for a None check.
  6. What are mutable default argument risks? A list created as a default parameter is reused between calls; use None and create a new list inside.

Functions, iteration and errors: questions 7–12

  1. *args and **kwargs? They collect extra positional arguments into a tuple and keyword arguments into a dictionary.
  2. What is a generator? A function using yield to produce values lazily; useful for large sequences.
  3. What is a list comprehension? Concise syntax for building a list, for example [x*x for x in range(5)]. Prefer readable expressions.
  4. How does exception handling work? try/except catches expected exceptions; else runs on success and finally runs during cleanup.
  5. What is a context manager? A with block manages setup and cleanup, commonly closing files reliably.
  6. Local vs global scope? Assignment inside a function generally creates a local name unless global or nonlocal is declared.

OOP and technical topics: questions 13–20

  1. Class vs instance? A class defines behavior; an instance is a particular object.
  2. What is inheritance? A class can reuse or extend behavior from a base class. Prefer composition where it fits better.
  3. What is __init__? An initializer executed when an instance is created.
  4. Shallow vs deep copy? A shallow copy duplicates the outer container but shares nested objects; deep copy recursively copies objects when supported.
  5. What is a decorator? A callable wrapping or modifying another callable, often used for logging or access checks.
  6. What is the GIL? In common CPython builds it limits simultaneous execution of Python bytecode by threads; implementation and version matter, so do not treat it as a universal property of Python.
  7. What is PEP 8? A Python style guide, not a correctness checker.
  8. How do you manage dependencies? Use isolated virtual environments and reproducible dependency specifications; avoid committing credentials.

Three small Python coding exercises

1. Count character frequencies

def frequencies(text):
    counts = {}
    for char in text:
        counts[char] = counts.get(char, 0) + 1
    return counts

print(frequencies('banana'))

Expected result: {‘b’: 1, ‘a’: 3, ‘n’: 2}. Explain that lookup is typically O(1) on average and the overall pass is O(n) on average.

2. Find the second distinct largest number

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

print(second_largest([4, 8, 8, 3]))  # 4

Explain duplicates and the fewer-than-two-distinct-values edge case. Sorting takes O(n log n) in the usual bound.

3. Reverse words, not letters

def reverse_words(text):
    return ' '.join(text.split()[::-1])

print(reverse_words('learn Python today'))

Output: today Python learn. split() normalizes whitespace, so this method does not preserve original spacing.

Seven-day practice plan

DayTopicDeliverable
1Strings, lists, tuplesFive small programs
2Dictionaries and setsCounting and membership exercises
3Functions and scopeExplain two tricky examples
4OOPSmall class with tests
5Files and exceptionsSafe input/output exercise
6Basic algorithmsTimed easy problems
7Mock interviewExplain code and tradeoffs aloud

Frequently asked questions

Is Python enough to get a developer job?

Python is a starting skill; many roles also need SQL, APIs, Git, testing and problem solving.

Should I memorize answers?

Understand each concept and write a working example. Recruiters may change the scenario.

Will companies ask these exact questions?

Not necessarily. Review the official job description and selection guidance.

More Python interview examples with explanations

Why does a mutable default argument keep state?

Consider this function:

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

print(add_tag("api"))
print(add_tag("sql"))

Its second call reuses the default list, producing two tags. Defaults are evaluated when the function is defined, not each time it is called. A safer version uses tags=None, then assigns a new empty list inside the function if needed. Explain that deliberately shared state can be useful but should not be hidden accidentally in a default value.

What is the difference between a shallow and deep copy?

import copy
original = [[1], [2]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0].append(9)
print(shallow)  # [[1, 9], [2]]
print(deep)     # [[1], [2]]

A shallow copy duplicates the outer list while preserving references to nested lists. Deep copying recursively copies supported nested objects. For large data structures, consider the extra memory and time cost.

How should exceptions be handled?

def parse_age(value):
    try:
        age = int(value)
    except (TypeError, ValueError) as exc:
        raise ValueError("Age must be an integer") from exc
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

Catch only expected errors, validate domain constraints separately and avoid returning a misleading default for every failure. In a service, translate validation errors into appropriate API responses rather than exposing private stack traces.

Understanding Python collections through real scenarios

ScenarioChooseWhy
Maintain ordered tasks that changelistSupports indexing and updates
Represent a fixed coordinate pairtupleExpresses a stable grouping
Check whether a username appearedsetUnique elements and efficient average membership checks
Look up order details by IDdictMaps unique hashable keys to values

For interviews, describe the data structure’s behavior before quoting complexity. Dictionaries typically have constant-time average lookup, but pathological collisions, memory use and data layout can change practical performance.

Scenario exercise: process a list of orders

Assume an application receives fictional order records containing id, amount and status. Write a function that totals the amounts of completed orders, ignores invalid records only according to an explicit business rule, and reports duplicate order IDs. Ask whether negative amounts represent refunds before choosing to reject them. The interviewer is checking your handling of requirements as much as your syntax.

A good solution should separate parsing from calculation, provide predictable behavior for an empty list, and include simple tests. For instance: empty input returns a zero total; a missing amount produces a clear validation error; duplicate identifiers are detected rather than silently counted twice. Explain whether you use Decimal instead of floating point for currency and why binary floating point can introduce rounding surprises.

How to explain your answer in an interview

  1. Restate the inputs, expected outputs and assumptions.
  2. Ask about edge cases such as empty input, duplicates and malformed records.
  3. Describe a simple approach before coding.
  4. Test with one normal case and at least two edge cases.
  5. State the time and space complexity without claiming an unmeasured speedup.

Quick self-assessment checklist

Can you explain the meaning of is None? Can you predict when a generator yields its next value? Can you use a context manager to close a file? Can you write and test a class with one method? Can you articulate when pandas or SQL would be more appropriate than manually iterating millions of rows? If not, build one small demonstration for each gap.

For authoritative language behavior, consult the official Python tutorial, and verify library syntax against the version you use.

Additional Python practice: test your reasoning

Exercise 1: count unique valid email domains

Given a list of fictional email addresses, extract the domain portion only when an address contains exactly one @ and both sides are nonempty. Normalize the domain to lowercase and return a set of distinct valid-looking domains. This simplified exercise is not a complete email validator.

def unique_domains(addresses):
    domains = set()
    for address in addresses:
        parts = address.strip().split("@")
        if len(parts) == 2 and all(parts):
            domains.add(parts[1].lower())
    return domains

sample = ["a@Example.com", "b@example.com", "invalid"]
print(unique_domains(sample))  # {'example.com'}

Discuss why a set fits the task and what happens if the input contains whitespace or internationalized addresses. Distinguish a coding exercise’s simplified rules from production-grade validation.

Exercise 2: filter records safely

Suppose a list contains dictionaries with an optional integer score field. Select records scoring at least 70. A correct program should decide how to handle a missing score, a string score and a boolean value before implementing comparisons. Python treats booleans as a subclass of integers, which is one reason explicit domain validation can matter.

Exercise 3: read a large file without loading it fully

Use with open(path, encoding="utf-8") as handle: and iterate over lines. Explain that streaming reduces peak memory consumption, whereas read() places the entire file contents in memory. Discuss how to report decoding errors and why user-controlled filenames must be handled cautiously.

A practical mock interview script

Interviewer: How would you find the first repeated number in a list? Candidate: I would maintain a set of values already seen, iterate from left to right and return the first element already in the set. If nothing repeats, I return None. This needs O(n) expected time and up to O(n) auxiliary space, assuming typical set performance. I would ask whether “first repeated” means first second occurrence or the duplicated value appearing earliest by original position because those definitions may differ.

Interviewer: What if memory is severely limited? Candidate: I would discuss sorting a copy if order can be discarded, an O(n²) scan for constant extra storage, or special constraints on the number range that permit alternatives. I would not promise a universal O(n) solution with constant memory for arbitrary objects.

Common Python interview pitfalls

  • Using is to compare equal strings or numbers rather than object identity.
  • Removing entries from a list while iterating over it without accounting for shifting indexes.
  • Confusing sort(), which mutates a list, with sorted(), which returns a new list.
  • Calling every comprehensions-based solution faster without measurement.
  • Failing to specify how null, empty or malformed input should be handled.

After each exercise, write at least three small tests: one normal case, one boundary case and one invalid-input case. The goal is not memorizing output but demonstrating how you reason about requirements.

Further reading

Strengthen your foundations with Hiring365’s 30-day DSA roadmap and SQL interview questions. Find suitable entry-level opportunities on Hiring365, and verify job details through the employer’s official portal.

Image credit: Chris Ried / Unsplash.

Scroll to Top