Python Interview Questions and Answers

33 questions with short, clear answers · Updated December 2026

Python is asked about in interviews for developer, data, automation, DevOps and AI roles. These questions start with the core language that every fresher is tested on and move to the concepts experienced candidates are expected to explain, such as decorators, generators, the GIL and memory, ending with short coding questions.

For coding questions, interviewers care about how you think as much as the final answer: say your approach out loud, then write clean code and test it with an edge case.

Python basics and data types

Q1. What are the key features of Python?

Python is a high-level, interpreted (compiled to bytecode and run by a virtual machine), dynamically typed, garbage-collected language with simple, readable syntax. It supports procedural, object-oriented and functional styles, has a large standard library and a huge ecosystem of packages, which is why it is used for web development, automation, data analysis, machine learning and DevOps scripting.

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

Mutable objects can be changed in place: list, dict, set and most class instances. Immutable objects cannot: int, float, str, tuple, frozenset and bytes; "changing" them creates a new object. Only immutable (hashable) objects can be dictionary keys or set members, and mutable default arguments cause a well-known bug.

Q3. What is the difference between a list and a tuple?

A list is mutable, written with square brackets, and used for collections that change. A tuple is immutable, written with parentheses, slightly faster and smaller, hashable if its items are, so it can be a dictionary key; it is used for fixed records such as coordinates or function return values.

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

== compares values (it calls __eq__); is checks whether two names point to the same object in memory. Use is only for singletons such as None (if x is None). Small integers and some strings may be cached so is can appear to work for them, but you should not rely on that.

Q5. How are dictionaries implemented, and are they ordered?

A dict is a hash table: keys are hashed to find their slot, so lookup, insert and delete are O(1) on average. Since Python 3.7 dictionaries keep insertion order as part of the language. Keys must be hashable; values can be anything.

Q6. What are list, dict and set comprehensions?

A short way to build a collection from an iterable, optionally with a condition: [x * x for x in nums if x > 0], {name: len(name) for name in names}, {w.lower() for w in words}. They are usually faster and more readable than a loop with append. A generator expression uses parentheses and produces items lazily.

Q7. What is the difference between a shallow copy and a deep copy?

A shallow copy (list.copy(), copy.copy(), slicing) creates a new outer object but shares the inner objects, so changing a nested list affects both. A deep copy (copy.deepcopy) recursively copies everything, so the copies are fully independent.

Functions

Q8. What are *args and **kwargs?

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, so a function can accept a variable number of arguments. The same symbols unpack when calling: f(*my_list, **my_dict). They are common in decorators and wrapper functions that pass arguments through.

Q9. Why is a mutable default argument a problem?

Default values are evaluated once, when the function is defined, so def add(item, items=[]) shares the same list across all calls and keeps growing. Use None as the default and create the list inside: if items is None: items = [].

Q10. How does Python pass arguments to functions?

By object reference ("pass by assignment"): the parameter name is bound to the same object the caller passed. If the object is mutable and the function changes it in place, the caller sees the change; rebinding the parameter to a new object does not affect the caller.

Q11. What is a lambda function?

A small anonymous function written as a single expression: lambda x: x * 2. It is mostly used as a short argument to functions such as sorted(items, key=lambda p: p["price"]), map or filter. For anything longer, a normal def function is clearer.

Q12. Explain the LEGB scope rule.

Python looks up a name in this order: Local (inside the current function), Enclosing (outer functions, for nested functions), Global (module level) and Built-in. To assign to a global name inside a function you need the global keyword, and to assign to an enclosing function's variable you need nonlocal.

Q13. What are type hints, and does Python enforce them?

Type hints (def total(prices: list[float]) -> float) document the expected types and let tools such as mypy, Pyright and editors catch errors before running the code. Python itself does not enforce them at run time; libraries such as Pydantic and FastAPI use them for validation.

Object-oriented programming

Q14. What is self, and what does __init__ do?

self is the instance a method is called on; Python passes it automatically as the first argument, so obj.method() becomes Class.method(obj). __init__ initialises a new instance's attributes after the object is created (the object itself is created by __new__).

Q15. What is the difference between an instance method, a class method and a static method?

An instance method takes self and works with one object's data. A @classmethod takes cls and works with the class, often as an alternative constructor (Date.from_string(...)). A @staticmethod takes neither; it is a plain function placed in the class because it belongs there logically.

Q16. How does inheritance work, and what is the MRO?

A class can inherit from one or more parent classes and override their methods; super() calls the next implementation. With multiple inheritance, Python uses the Method Resolution Order (C3 linearisation) to decide which class's method is used; ClassName.__mro__ shows it.

Q17. What are dunder (magic) methods?

Methods with double underscores that Python calls for built-in behaviour: __str__ and __repr__ for printing, __len__ for len(), __eq__ and __lt__ for comparisons, __add__ for +, __getitem__ for indexing, __iter__ for loops and __enter__/__exit__ for with blocks. Implementing them makes your objects behave like built-in types.

Q18. What are dataclasses?

The @dataclass decorator generates __init__, __repr__ and __eq__ from annotated class attributes, which removes boilerplate for classes that mainly hold data. Options such as frozen=True (immutable), order=True and slots=True add more behaviour.

Generators, decorators and concurrency

Q19. What is the difference between an iterator and a generator?

An iterator is any object with __iter__ and __next__ that returns items one at a time and raises StopIteration at the end. A generator is an easy way to create one: a function with yield, which pauses and resumes, producing values lazily. Generators use little memory, so they suit large files or infinite sequences.

Q20. What is a decorator?

A decorator is a function that takes a function and returns a new function that adds behaviour around it, applied with @name above the definition. Common uses are logging, timing, caching (functools.lru_cache), access checks and retries. Use functools.wraps inside it to keep the original function's name and docstring.

Q21. What is a context manager?

An object used with a with statement that sets something up and guarantees clean-up, even if an exception happens: with open("f.txt") as f closes the file automatically. You write one with __enter__ and __exit__, or with the @contextmanager decorator and a single yield. Locks, database transactions and temporary directories are common examples.

Q22. What is the GIL, and how does it affect multithreading?

The Global Interpreter Lock in CPython lets only one thread run Python bytecode at a time, so threads do not speed up CPU-heavy work, though they still help with I/O-bound work because the lock is released while waiting. For CPU-heavy work use multiprocessing or libraries that release the GIL, such as NumPy. Python 3.13 added an optional free-threaded build without the GIL, and 3.14 made it officially supported, but the standard build still has the GIL.

Q23. When would you use threading, multiprocessing or asyncio?

asyncio for many concurrent I/O operations (thousands of network calls) in a single thread using async and await; threading for I/O-bound work with libraries that are not async; multiprocessing (or concurrent.futures.ProcessPoolExecutor) for CPU-bound work, because separate processes each have their own interpreter and GIL.

Q24. How does Python manage memory?

CPython uses reference counting: each object counts how many references point to it and is freed when the count reaches zero. A cyclic garbage collector (the gc module) cleans up objects that reference each other in cycles. Memory for small objects comes from Python's own allocator, and tools such as tracemalloc help find leaks.

Errors, modules and environments

Q25. How does exception handling work in Python?

Code that may fail goes in try; except catches specific exception types (catch the narrowest type, not a bare except); else runs if no exception occurred; finally always runs, for clean-up. raise throws an exception, and raise ... from e keeps the original cause. Custom exceptions are classes that inherit from Exception.

Q26. What is if __name__ == "__main__" for?

When a file is run directly, its __name__ is "__main__"; when it is imported, __name__ is the module name. Putting the start-up code under this check lets the file work both as a script and as an importable module without running that code on import.

Q27. Why use a virtual environment, and how do you manage dependencies?

A virtual environment (python -m venv .venv) gives each project its own interpreter and packages, so projects needing different versions do not clash and the system Python stays clean. Dependencies are declared in pyproject.toml or requirements.txt and pinned with a lock file; tools such as pip, uv and Poetry install them reproducibly.

Q28. How do you read a large file without running out of memory?

Iterate over the file object line by line (for line in f), which reads one line at a time, instead of f.read() or f.readlines(). For binary files read fixed-size chunks in a loop, and for large CSVs use pandas with chunksize or a streaming parser. Generators keep the whole pipeline lazy.

Q29. How do you test Python code?

With pytest (or the built-in unittest): write small functions named test_* that use assert, use fixtures for setup, parametrize to cover many inputs, and unittest.mock to replace network or database calls. Run tests in CI on every change and measure coverage with coverage.py.

Coding questions

Q30. Reverse a string and check whether it is a palindrome.

Slicing reverses a string: s[::-1]. A palindrome check that ignores case and spaces: clean = "".join(ch.lower() for ch in s if ch.isalnum()); return clean == clean[::-1]. Mention that this is O(n) in time and space, and that a two-pointer loop avoids the extra copy.

Q31. Count how often each word appears in a text.

from collections import Counter; counts = Counter(text.lower().split()); counts.most_common(5) gives the top five. Without Counter, loop over the words and use counts[w] = counts.get(w, 0) + 1. For real text, strip punctuation first, for example with re.findall(r"\w+", text.lower()).

Q32. Find two numbers in a list that add up to a target.

Use a dictionary of seen values: for i, n in enumerate(nums): if target - n in seen: return seen[target - n], i; seen[n] = i. This is O(n) time instead of the O(n²) nested loop, and it is a classic question to show you know how hash lookups trade memory for speed.

Q33. Remove duplicates from a list while keeping the order.

list(dict.fromkeys(items)) keeps the first occurrence of each item in order, because dictionaries preserve insertion order. list(set(items)) also removes duplicates but loses the order. Both need hashable items.

Learn Python hands-on

Knowing the answers is half the job; interviewers also ask what you have built. Technical Guftgu's Python training is taught in Hindi with live classes, labs and project work, plus resume and mock-interview help. We do not promise or guarantee job placement.

Python training near you

More interview questions

TECHNICAL GUFTGU

© 2026 Technical Guftgu. All rights reserved.