Python Interview
Questions & Answers
π±Beginner QuestionsQ1βQ10
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. It emphasises code readability and simplicity β Python code often reads almost like plain English.
- Readable syntax: Indentation-based structure forces clean, consistent code.
- Versatile: Used in web development, data science, AI/ML, automation, scripting, and more.
- Huge ecosystem: PyPI has over 400,000 packages β there's a library for almost everything.
- Interpreted: No compilation step β run code directly, making development faster.
- Cross-platform: Runs on Windows, macOS, and Linux without modification.
- Strong community: One of the most popular languages in the world with vast documentation.
Python has several built-in data types grouped by category:
| Feature | List | Tuple | Set |
|---|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} |
| Mutable | β Yes | β No | β Yes |
| Ordered | β Yes | β Yes | β No |
| Duplicates | β Allowed | β Allowed | β Not allowed |
| Indexable | β Yes | β Yes | β No |
| Use case | Ordered mutable data | Fixed data, dict keys | Unique items, fast lookup |
A list comprehension is a concise, Pythonic way to create lists from existing iterables in a single line. Syntax: [expression for item in iterable if condition]
== and is in Python?==(equality): Checks if two objects have the same value.is(identity): Checks if two variables point to the same object in memory (sameid()).
is only to compare against None, True, or False. Use == for everything else. Never use is to compare strings or integers.*args and **kwargs in Python?*args and **kwargs let functions accept a variable number of arguments.
Mutable objects can be changed after creation. Immutable objects cannot β any "modification" creates a new object.
None as default, then assign the mutable inside the function.A lambda is an anonymous, single-expression function defined with the lambda keyword. It's used when you need a short function for a brief period β typically as an argument to higher-order functions.
Python uses try/except/else/finally blocks to handle runtime errors gracefully without crashing the program.
range() and enumerate() functions?range() generates a sequence of numbers. enumerate() adds a counter to an iterable β both are commonly used in loops.
β‘Intermediate QuestionsQ11βQ21
A decorator is a function that wraps another function to add behaviour before or after it runs, without modifying the original function's code. They use the @ syntax.
A generator is a function that uses yield instead of return. It produces values one at a time, pausing and resuming execution β making it memory-efficient for large sequences.
Object-Oriented Programming organises code around objects β instances of classes. Python's four OOP pillars are Encapsulation, Inheritance, Polymorphism, and Abstraction.
map(), filter(), and reduce() functions?The GIL (Global Interpreter Lock) is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core processors. It exists to protect Python's memory management from race conditions.
- Impact on CPU-bound tasks: Threading doesn't give true parallelism for CPU-heavy code. Use
multiprocessinginstead. - Impact on I/O-bound tasks: The GIL is released during I/O operations, so threading works well for network requests, file reading, etc.
- Workarounds: Use
multiprocessing(separate processes, each with own GIL), orasynciofor I/O concurrency.
@staticmethod and @classmethod?| Feature | @staticmethod | @classmethod |
|---|---|---|
| First parameter | None (no implicit) | cls (the class) |
| Access to class | β No | β Yes via cls |
| Access to instance | β No | β No |
| Use case | Utility/helper functions | Alternative constructors, class-level ops |
Dunder (double underscore) methods, also called magic methods, allow classes to define how they behave with built-in Python operations like +, len(), print(), and comparisons.
with statement and context managers?The with statement ensures that setup and teardown code runs reliably β even if an exception occurs. It's used for resource management (files, database connections, locks).
append(), extend(), and insert() for lists?zip() and any() / all() built-ins?π₯Advanced QuestionsQ22βQ30
A metaclass is the "class of a class" β it defines how classes themselves are created. Just as objects are instances of classes, classes are instances of metaclasses. The default metaclass in Python is type.
Python manages memory automatically through two mechanisms:
- Reference counting: Every object tracks how many references point to it. When the count drops to zero, the memory is immediately freed.
- Cyclic garbage collector: Handles reference cycles (where two objects reference each other) that reference counting alone can't clean up.
A descriptor is an object that defines how attribute access works on another class, by implementing __get__, __set__, and/or __delete__. They power Python's @property, @classmethod, and @staticmethod.
asyncio and how does Python handle asynchronous programming?asyncio is Python's built-in library for writing concurrent I/O-bound code using coroutines β functions defined with async def and awaited with await. It runs in a single thread using an event loop.
multiprocessing or concurrent.futures.ProcessPoolExecutor.__slots__ and when should you use them?By default, Python stores instance attributes in a per-instance __dict__ dictionary β flexible but memory-heavy. __slots__ replaces this with a fixed, compact array, reducing memory usage significantly.
Use __slots__ when: creating many instances of a class (e.g., data records, coordinates, nodes in a large graph), and you don't need to add arbitrary attributes dynamically.
__new__ and __init__?__new__: Called first β responsible for creating and returning the new object instance. Takesclsas first argument.__init__: Called after β responsible for initialising the already-created instance. Takesself.
Type hints (PEP 484, Python 3.5+) let you annotate variables and function signatures with expected types. Python doesn't enforce them at runtime, but they improve code readability, catch bugs early via static analysis tools like mypy, and power IDE autocompletion.
deepcopy, pickling, and serialisation in Python?| Method | Purpose | Output | Use case |
|---|---|---|---|
copy.deepcopy() | Clone object in memory | Python object | Avoid shared references in RAM |
pickle | Serialize to bytes | Binary bytes | Save/send Python objects |
json | Serialize to string | JSON string | APIs, cross-language interchange |
Dataclasses (Python 3.7+) automatically generate boilerplate methods (__init__, __repr__, __eq__) for classes that primarily store data.
__init__, or inheritance hierarchies where dataclass inheritance gets complex.Up Next: React Interview Questions
You've covered Python. Next in the series is React β hooks, virtual DOM, state management, and component patterns. Coming soon to RankWeb3.
β Git & GitHub Q&A