New · Cohort 3Engineering Analytics Cohort 3 goes live 25 July — only 30 seatsRegister Now
Python Interview Questions

Python Interview Questions and Answers for Data and Automation Roles

Practice Python interview questions covering basics, data structures, functions, exceptions, file handling, comprehensions, OOP basics, pandas, and data-role coding.

Published by PrepNPlaced. Last updated 2026-05-31. Preparation guidance, not a hiring guarantee.

Guide

What To Learn And How To Practice

Python basics interviewers check

For data roles, Python rounds often test readable problem solving, data structures, file handling, and whether you can write code that handles edge cases.

Lists, dictionaries, sets, tuples, and when to use each
Functions, arguments, return values, and scope
Exceptions, file reading, and input validation

Sample questions and answer hints

Practice explaining your approach before coding. A clear brute-force answer with edge cases is better than a clever answer you cannot debug.

Count word frequency from a text file
Group records by category using a dictionary
Remove duplicates while preserving order

Frequency hint

Normalize text, split into tokens, use a dictionary or Counter, and decide how to handle punctuation.

Data cleaning hint

State how you handle missing values, type conversion, invalid dates, and duplicate rows.

Data-role Python practice

For analytics and data engineering, Python questions may involve parsing files, calling APIs, transforming rows, or explaining pandas-style operations.

Read CSV or JSON safely
Transform records into a new schema
Explain apply, groupby, merge, and vectorized operations at a practical level

Common mistakes

Many candidates lose points by ignoring edge cases, mutating inputs unexpectedly, writing unreadable one-liners, or not explaining complexity.

No handling for empty input
Confusing shallow and deep copies
Using broad exceptions without explaining why

Python interview questions with sample answers

Answered questions that come up repeatedly in data and automation rounds. Aim for a clear, correct explanation over a clever one-liner.

Data structures and copies
Comprehensions and generators
Practical pandas reasoning

List vs tuple

Lists are mutable; tuples are immutable and hashable, so a tuple can be a dict key or set member and signals a fixed record. Use a tuple when the collection should not change.

Shallow vs deep copy

copy.copy() copies the outer object but shares nested objects, while copy.deepcopy() recursively copies everything. After a shallow copy, mutating a nested list changes both copies.

is vs ==

== compares values; is compares identity (the same object in memory). Use == for equality and reserve is for checks like 'if x is None'.

Mutable default argument trap

def f(x, acc=[]) reuses the same list across calls because the default is created once. Use acc=None, then set acc = acc or [] inside the function.

Count word frequency from a file

Read the file, lower-case and split into tokens, then use collections.Counter(tokens). Counter.most_common(n) returns the top n words; decide how to strip punctuation first.

Generators vs lists

A generator yields items lazily with near-constant memory, ideal for large or streaming files; a list holds everything at once. Use yield or a generator expression for big data.

Remove duplicates preserving order

Use dict.fromkeys(items) which keeps first-seen order, or loop with a seen set. A plain set() removes duplicates but loses order.

groupby and merge in pandas

df.groupby('key')['val'].agg(...) splits rows by key and aggregates each group; pd.merge(a, b, on='key', how='left') joins like SQL. Watch many-to-many keys, which inflate row counts.

Question bank

22 interview questions with answers

Real questions from beginner to advanced, each with a concise model answer — practice them, then rehearse live in a mock interview.

BeginnerWhat is the difference between a list and a tuple in Python?

A list is mutable — you can add, remove, and change elements — and uses square brackets. A tuple is immutable and uses parentheses, making it slightly faster and usable as a dictionary key. Use tuples for fixed collections.

BeginnerWhat is the difference between a list and a set?

A list is an ordered, indexable collection that allows duplicates. A set is an unordered collection of unique elements with fast membership tests (O(1) on average). Use a set to deduplicate or check existence quickly.

BeginnerWhat are mutable and immutable types in Python?

Mutable objects (list, dict, set) can change in place; immutable objects (int, str, tuple, frozenset) cannot. Immutability matters for hashability, safe sharing, and avoiding surprising side effects when passing objects to functions.

BeginnerWhat is the difference between '==' and 'is'?

'==' compares values for equality; 'is' compares identity — whether two references point to the same object in memory. Use '==' for value checks and 'is' mainly for comparisons with None.

BeginnerWhat is a list comprehension?

A concise way to build a list from an iterable in one expression, e.g. [x*x for x in range(10) if x % 2 == 0]. It's more readable and often faster than an equivalent for-loop with append.

BeginnerWhat are *args and **kwargs?

*args lets a function accept any number of positional arguments as a tuple; **kwargs accepts any number of keyword arguments as a dictionary. They make functions flexible and are used to forward arguments to other functions.

BeginnerHow does Python manage memory?

Python uses automatic memory management with reference counting plus a cyclic garbage collector to reclaim objects with circular references. An object is freed when its reference count drops to zero.

IntermediateWhat is the difference between a generator and a list?

A list holds all its elements in memory at once. A generator (using yield or a generator expression) produces items lazily, one at a time, so it's memory-efficient for large or streaming data. Generators can only be iterated once.

IntermediateWhat is a decorator in Python?

A decorator is a function that wraps another function to extend its behavior without changing its code, applied with the @ syntax. Common uses include logging, timing, caching (@lru_cache), and access control.

IntermediateWhat is the Global Interpreter Lock (GIL)?

The GIL is a mutex in CPython that lets only one thread execute Python bytecode at a time, so threads don't speed up CPU-bound work. Use multiprocessing for CPU-bound parallelism; threads still help for I/O-bound tasks.

IntermediateWhat is the difference between a shallow copy and a deep copy?

A shallow copy (copy.copy) copies the outer object but shares references to nested objects, so changing a nested item affects both. A deep copy (copy.deepcopy) recursively copies everything, producing a fully independent object.

IntermediateHow does exception handling work in Python?

Wrap risky code in try, catch specific exceptions with except, run cleanup in finally, and use else for code that runs only when no exception occurred. Catch specific exception types rather than a bare except.

IntermediateWhat is a context manager and the 'with' statement?

A context manager defines setup and teardown via __enter__ and __exit__ (or @contextmanager), and the with statement guarantees the teardown runs even on error. It's commonly used to open and reliably close files or connections.

IntermediateWhat is the mutable default argument pitfall?

Default arguments are evaluated once at definition time, so a mutable default like def f(x=[]) is shared across calls and accumulates state. The fix is to default to None and create the list inside the function.

IntermediateWhat are Python's key data structures for data work?

Lists and dicts for general use, sets for uniqueness and membership, tuples for fixed records, and collections types like Counter, defaultdict, and deque. For tabular data, pandas DataFrames and NumPy arrays are standard.

IntermediateWhat is the difference between map, filter, and a list comprehension?

map applies a function to each item, filter keeps items passing a predicate, and both return lazy iterators. A list comprehension can do both in one readable expression and is usually preferred in modern Python.

IntermediateHow do you merge two dictionaries in Python?

In Python 3.9+ use dict1 | dict2. Earlier you can use {**dict1, **dict2} or dict1.update(dict2). Keys in the second dictionary overwrite duplicates from the first.

AdvancedWhat is the difference between iterators and iterables?

An iterable is any object you can loop over (it implements __iter__); an iterator is the object that produces values one at a time via __next__ and remembers its position. iter() turns an iterable into an iterator.

AdvancedHow would you process a file that doesn't fit in memory?

Process it lazily: iterate the file object line by line, read in fixed-size chunks, or use generators so only a small portion is in memory at once. For tabular data, use pandas' chunksize or move to Dask/PySpark.

AdvancedWhat are Python closures and when are they useful?

A closure is a nested function that remembers variables from its enclosing scope even after that scope has returned. They power factory functions, decorators, and lightweight stateful callbacks without a full class.

AdvancedHow do you optimize slow pandas code?

Use vectorized operations instead of row-wise apply or loops, choose efficient dtypes (category, downcast numerics), filter early, avoid chained indexing, and use groupby/merge instead of manual iteration. For very large data, move to Dask or PySpark.

AdvancedWhat is the difference between multithreading and multiprocessing in Python?

Multithreading shares memory but is limited by the GIL for CPU-bound work, so it mainly helps I/O-bound tasks. Multiprocessing spawns separate processes with their own memory, giving true parallelism for CPU-bound work at higher overhead.

FAQ

Common Questions

Do data roles need advanced Python?

Most entry and mid-level data roles need strong basics, data structures, file handling, API/CSV work, and practical pandas-style transformation.

Should I memorize Python syntax?

Memorize fundamentals, but prioritize explaining approach, edge cases, and why a data structure is appropriate.

Are pandas and NumPy always tested?

Not always. They are common in data analyst and data science workflows, but many interviews still test core Python first.

How do I practice Python for data engineering?

Build scripts that read data, validate it, transform it, and write clean output. Then explain failure handling.

What mistakes should I avoid?

Avoid unclear one-liners, missing edge cases, broad exception swallowing, and claims about libraries you have not used.

How can PrepNPlaced help?

Use Open Learning for revision, AI Mock Interview for practice, and Resume AI to turn Python projects into honest resume proof.

Next Step

Turn The Guide Into Practice

Use PrepNPlaced tools to turn this learning path into resume proof, targeted practice, and interview-ready explanations.

Practice AI Mock Interview