Advertisement

Information Technology

Python Interview Questions & Answers

General-purpose programming language for AI, data science, and web development.

20topics 300questions last updated
Advertisement

Async Generators & Async Context Managers

All 15 questions
  1. An async generator is a function defined with 'async def' that uses 'yield' inside it, producing an object supporting the asynchronous iteration protocol (__anext__) instead of the…

  2. 'async for' is the asynchronous equivalent of a regular 'for' loop — it awaits each call to the generator's __anext__() method, pausing until the next value is ready, and must itse…

  3. An async context manager implements __aenter__ and __aexit__ (both coroutines, defined with 'async def') instead of the synchronous __enter__/__exit__ — used with 'async with' to m…

  4. asynccontextmanager decorates a single async generator function: code before the 'yield' runs as __aenter__, the yielded value becomes the 'as' target, and code after 'yield' (typi…

  5. Just like a regular generator, wrapping the yield in a try/finally inside an async generator guarantees the finally block runs when the generator is exhausted, explicitly closed vi…

Command-Line Interfaces (argparse)

All 15 questions
  1. Instantiate argparse.ArgumentParser(), call add_argument() for each expected argument, then call parse_args() to parse sys.argv and return a Namespace object with the parsed values…

  2. A positional argument is REQUIRED and identified by its ORDER on the command line (declared without a leading dash); an optional argument is identified by a FLAG name (starting wit…

  3. Pass 'default=' to set the value used when the argument is omitted, and 'type=' to specify a callable (like int, float, or a custom function) that argparse applies to convert the r…

  4. Pass 'choices=[...]' to restrict the argument to a specific set of allowed values — argparse automatically validates the input against this list and prints a helpful error message…

  5. Set 'nargs' to control how many values an argument consumes: '+' requires ONE OR MORE, '*' allows ZERO OR MORE, and a specific integer requires EXACTLY that many — the parsed resul…

Comprehensions & Generators

All 15 questions
  1. A list comprehension `[expr for item in iterable]` builds a new list in one concise expression, evaluating 'expr' for each item — functionally equivalent to a for loop that appends…

  2. Add an 'if condition' clause after the 'for' clause; only items for which the condition is truthy are included in the resulting list, exactly like a for loop with a nested 'if' bef…

  3. A generator function contains at least one 'yield' statement; calling it doesn't run the function body immediately — it returns a generator object, and the body only executes incre…

  4. A dict comprehension uses curly braces with a 'key: value' pair (`{k: v for ...}`), producing a dictionary; a set comprehension uses curly braces with just an expression (`{expr fo…

  5. A generator expression uses parentheses `(expr for item in iterable)` instead of square brackets, and produces a LAZY generator object (computing values one at a time on demand) ra…

Concurrency (asyncio/threading/multiprocessing)

All 15 questions
  1. Concurrency means multiple tasks make PROGRESS over overlapping time periods (not necessarily simultaneously); parallelism means tasks run LITERALLY AT THE SAME INSTANT on differen…

  2. Create a threading.Thread object, passing the target function (and optional args), then call .start() to begin execution concurrently, and .join() to wait for it to finish before c…

  3. Define your entry-point coroutine with 'async def', then call asyncio.run(coroutine()) from regular (synchronous) code — this creates a new event loop, runs the coroutine to comple…

  4. The GIL ensures only ONE thread executes Python bytecode at any given instant, so CPU-bound multithreaded code gets NO real speedup (and can even be slightly slower due to lock ove…

  5. asyncio.gather(*coroutines) schedules all given coroutines to run CONCURRENTLY on the event loop and returns a single awaitable that resolves once ALL of them complete, collecting…

Data Types & Structures

All 15 questions
  1. A list is MUTABLE (elements can be added, removed, or changed after creation), created with square brackets; a tuple is IMMUTABLE (fixed once created), created with parentheses — t…

  2. A set stores only UNIQUE elements (duplicates are automatically discarded) and doesn't preserve insertion order in the general case; a list preserves both order AND duplicates — se…

  3. Access a value with dict[key] (raises KeyError if missing) or dict.get(key, default) (returns None or a default instead); add/update with dict[key] = value; remove with del dict[ke…

  4. A shallow copy (via list.copy(), dict.copy(), or copy.copy()) creates a NEW outer container but still references the SAME nested/inner objects — mutating a nested list inside a sha…

  5. list[start:stop:step] extracts a sub-list from index 'start' (inclusive) up to 'stop' (exclusive), advancing by 'step' — negative indices count from the END of the list, and a nega…

Dataclasses & NamedTuples

All 15 questions
  1. @dataclass automatically generates __init__ (accepting each declared field as a parameter), __repr__ (a readable string representation), and __eq__ (comparing all fields for equali…

  2. namedtuple(typename, field_names) creates a NEW tuple subclass whose elements can be accessed both by INDEX (like a regular tuple) and by NAMED ATTRIBUTE, combining a tuple's light…

  3. Assign a default value directly after the type annotation, exactly like a regular function parameter default — and just like function parameters, any field WITH a default must come…

  4. Using a mutable object (list, dict, set) as a default value would share the SAME object across every instance (the classic Python mutable-default-argument trap), so @dataclass expl…

  5. Pass frozen=True to the @dataclass decorator to make every field effectively read-only after __init__ runs — attempting to assign to any field afterward raises a FrozenInstanceErro…

Debugging & Profiling

All 15 questions
  1. Insert 'import pdb; pdb.set_trace()' (or the shorter 'breakpoint()' in Python 3.7+) at the line where you want execution to pause — this drops you into an interactive debugger prom…

  2. Use an f-string with the '=' specifier (Python 3.8+) to automatically print both the variable's NAME and its value in one concise expression, avoiding the tedium of manually typing…

  3. traceback.format_exc() returns the current exception's full traceback (including file names, line numbers, and the exception message) as a formatted string, letting you log or stor…

  4. timeit.timeit(stmt, number=N) runs the given code snippet N times (default 1,000,000) and returns the TOTAL time taken, automatically minimizing common measurement pitfalls (like g…

  5. Run your program (or a specific function call) through cProfile.run() or the command line (`python -m cProfile script.py`), which produces a detailed report showing call counts, cu…

  1. A decorator is a function that takes another function as input and returns a (usually modified or wrapped) function as output; `@decorator_name` above a function definition is pure…

  2. Define an outer function taking the target function as its parameter, define an inner 'wrapper' function that prints, calls the original function, and returns its result, then retu…

  3. Without @functools.wraps(func), the wrapper function REPLACES the original's __name__, __doc__, and other metadata with the WRAPPER's own — breaking introspection tools, debuggers,…

  4. Add an EXTRA outer layer: a function that takes the decorator's OWN arguments and returns the actual decorator function (which in turn takes the target function and returns the wra…

  5. A class-based decorator stores the wrapped function (typically in __init__) and implements __call__ to actually invoke it — useful when the decorator needs to maintain PERSISTENT s…

Descriptors & Properties

All 15 questions
  1. @property turns a method into a computed, READ-ONLY (by default) attribute — calling it WITHOUT parentheses runs the underlying method and returns its result, letting you expose co…

  2. Define a second method with the SAME name, decorated with @property_name.setter — this method runs whenever someone assigns to the property, letting you validate or transform the i…

  3. A descriptor is any object implementing __get__, __set__, and/or __delete__, placed as a CLASS attribute — when accessed through an instance, Python automatically calls these metho…

  4. A DATA descriptor implements BOTH __get__ AND __set__ (or __delete__); a NON-DATA descriptor implements ONLY __get__. Data descriptors take priority OVER an instance's __dict__ dur…

  5. __set_name__(self, owner, name) is automatically called by Python ONCE, at CLASS CREATION time, passing the owning class and the exact attribute name the descriptor was assigned to…

Exception Handling

All 15 questions
  1. Code in 'try' runs normally; if it raises an exception, Python looks for the FIRST 'except' clause matching that exception's type (checked top to bottom) and runs it — if none matc…

  2. Code in 'finally' ALWAYS runs after try (and any except) completes, whether an exception occurred or not, and even if the try block contains a 'return' — making it the standard pla…

  3. List the exception types as a TUPLE after 'except', separated by commas — the clause catches ANY of the listed types, running the same handling code regardless of which specific on…

  4. Define a class inheriting from Exception (or a more specific built-in exception), typically with no additional code needed at all (just 'pass') unless you want to add custom attrib…

  5. Plain 'raise NewException()' inside an except block still shows BOTH the original and new exception in the traceback (implicit chaining, labeled 'During handling of the above excep…

File I/O & Context Managers

All 15 questions
  1. 'with open(path) as f:' guarantees the file is properly closed when the block exits, EVEN IF an exception occurs inside it — manually calling open() and close() risks leaking the f…

  2. read() returns the ENTIRE file's contents as a single string; readline() returns just the NEXT single line (including its trailing newline); readlines() returns a LIST of every lin…

  3. 'r' opens for reading (default, error if the file doesn't exist); 'w' opens for writing, TRUNCATING (erasing) any existing content; 'a' opens for APPENDING to the end without erasi…

  4. Define a class with __enter__ (running setup logic and returning the value bound by 'as') and __exit__ (running cleanup logic, receiving any exception info that occurred inside the…

  5. Decorate a generator function with @contextmanager; code BEFORE the single 'yield' runs as __enter__ (the yielded value becomes the 'as' target), and code AFTER 'yield' (typically…

Functions & Scope

All 15 questions
  1. Positional arguments are matched to parameters by ORDER; keyword arguments are matched by explicit NAME (param=value), letting you pass arguments out of order and making the call s…

  2. A default value (`def func(param=default):`) is used when the caller omits that argument — critically, the default expression is evaluated ONCE, at FUNCTION DEFINITION time, not on…

  3. LEGB describes the order Python searches for a variable name: Local (the current function), Enclosing (any outer function, for closures), Global (the module level), and Built-in (P…

  4. Without 'global', assigning to a name inside a function creates a NEW LOCAL variable (shadowing the global one) rather than modifying the global — reading a global variable works f…

  5. 'nonlocal' tells Python that an assignment inside a nested function should modify the variable in the nearest ENCLOSING function's scope (not create a new local, and not reach all…

functools & Functional Programming Tools

All 15 questions
  1. functools provides higher-order functions that act on or return other functions, such as tools for caching (lru_cache, cache), partial application (partial), reducing sequences (re…

  2. partial creates a new callable with some positional or keyword arguments pre-filled, returning a function with a smaller remaining signature. It's useful for adapting a general fun…

  3. reduce(function, iterable, initializer) cumulatively applies a binary function to items of an iterable, reducing it to a single value. It's discouraged for complex logic because th…

  4. When a decorator replaces a function with a wrapper, the wrapper loses the original's __name__, __doc__, and other metadata. @functools.wraps(func) applied to the wrapper copies th…

  5. singledispatch turns a function into a generic function that dispatches to type-specific implementations registered with @func.register(Type). The base function acts as the default…

Iterators & the Iterator Protocol

All 15 questions
  1. An iterable is any object implementing __iter__() that returns an iterator, such as lists, tuples, and dicts -- you can loop over it repeatedly. An iterator is an object implementi…

  2. A custom iterator class defines __next__() to return the next value or raise StopIteration when exhausted, and __iter__() to return self so the object works directly in for-loops a…

  3. StopIteration signals that an iterator has no more values. A for-loop repeatedly calls next() on the iterator behind the scenes and automatically catches StopIteration to end the l…

  4. iter(callable, sentinel) repeatedly calls callable with no arguments and yields each result until the result equals sentinel, at which point iteration stops. This is useful for tur…

  5. If a class's __iter__ returns self, the object is both iterable and iterator, meaning it can only be iterated once -- a second for-loop over the same instance starts from wherever…

  1. logging supports severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), can be routed to multiple destinations (console, files, network) simultaneously, includes timestamps and c…

  2. DEBUG (detailed diagnostic info), INFO (confirmation things work as expected), WARNING (something unexpected but not fatal), ERROR (a serious problem, functionality failed), and CR…

  3. A Logger is the entry point your code calls (logger.info(...)); it passes log records to one or more Handlers, which decide where output goes (console, file, network). Each Handler…

  4. Using __name__ creates a logger named after the module's dotted path, forming a hierarchy that mirrors your package structure. This lets consumers of your code configure logging pe…

  5. RotatingFileHandler rotates the log file once it reaches a specified maxBytes, renaming old files with numeric suffixes and keeping up to backupCount old files. TimedRotatingFileHa…

Magic Methods & Operator Overloading

All 15 questions
  1. Magic methods are special methods surrounded by double underscores (e.g., __init__, __str__, __add__) that Python calls implicitly in response to built-in operations like construct…

  2. __str__ should return a readable, user-facing string (used by print() and str()), while __repr__ should return an unambiguous, ideally eval-able representation useful for debugging…

  3. Defining __add__(self, other) lets instances of your class respond to the + operator, and similarly __sub__, __mul__, __truediv__, etc. for other operators. Python calls left.__add…

  4. If two objects are equal (__eq__ returns True), they must have the same hash value so they behave consistently in sets and dict keys. By default, defining __eq__ without __hash__ m…

  5. __len__ enables len(obj); __getitem__ enables obj[key] (and, historically, iteration and 'in' checks via integer index fallback); __setitem__ enables obj[key] = value. Implementing…

Memory Management & Garbage Collection

All 15 questions
  1. CPython uses automatic reference counting as its primary memory management mechanism: every object tracks how many references point to it, and when that count drops to zero, the me…

  2. A reference cycle occurs when two or more objects reference each other (directly or indirectly), keeping their reference counts above zero even when nothing outside the cycle refer…

  3. CPython's gc module divides tracked objects into three generations (0, 1, 2) based on survival: new objects start in generation 0; objects that survive a collection are promoted to…

  4. weakref.ref (and weakref.proxy) creates a reference to an object that doesn't increase its reference count, so the referenced object can still be garbage collected even while the w…

  5. sys.getsizeof(obj) returns the memory size in bytes of the object itself, but not the objects it references -- a list of large strings might report a small size for the list contai…

Metaclasses & Class Customization

All 15 questions
  1. A metaclass is 'the class of a class' -- it defines how classes themselves are constructed, just as a class defines how instances are constructed. The default metaclass for all cla…

  2. type(name, bases, namespace) creates a new class object: name is the class's __name__ string, bases is a tuple of parent classes, and namespace is a dict of attributes and methods.…

  3. A custom metaclass subclasses `type` and overrides __new__ and/or __init__ to customize class creation itself -- for example, validating that subclasses implement required methods,…

  4. __init_subclass__(cls, **kwargs) is a classmethod automatically called whenever a subclass is defined, letting you hook into subclass creation (validation, registration, attribute…

  5. __class_getitem__(cls, item) is called when you subscript a class itself (not an instance), like `list[int]` or a custom `Container[str]`. It's primarily used to support type-hint…

Modules & Packaging

All 15 questions
  1. A module is a single .py file containing Python definitions and statements that can be imported. A package is a directory containing multiple modules plus an __init__.py file (maki…

  2. __init__.py marks a directory as a regular Python package and runs when the package is first imported, letting you control what's exposed at the package level (e.g., re-exporting s…

  3. Python caches every imported module in sys.modules keyed by its fully qualified name. When any code does `import foo`, Python checks sys.modules first; if already present, it reuse…

  4. An absolute import specifies the full path from the top-level package (`from mypackage.utils import helper`), while a relative import uses leading dots to reference modules relativ…

  5. When you import a module, Python searches directories listed in sys.path in order: the directory of the script being run (or '' for interactive/current directory), directories from…

Multiple Inheritance & MRO

All 15 questions
  1. Multiple inheritance lets a class inherit from more than one base class simultaneously, combining attributes and methods from all of them, unlike single inheritance where a class h…

  2. The diamond problem occurs when a class inherits from two classes that both inherit from a common ancestor, creating ambiguity about which inherited method version should be used.…

  3. super() doesn't literally mean 'my direct parent class' -- it returns a proxy that follows the class's MRO, calling the *next* class in that order relative to the current class. In…

  4. C3 linearization merges the MROs of a class's parents plus the list of parents itself, using a rule that a class only appears in the result once all classes that must precede it (p…

  5. A mixin is a class designed to provide a specific, self-contained piece of reusable functionality (like serialization, logging, or comparison behavior) to be combined with other cl…