Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. What are *args and **kwargs in Python?

    In a function definition, *args collects any extra positional arguments into a tuple, and **kwargs collects any extra keyword arguments into a dict. They let a function accept a variable number of inputs. The same * and ** symbols also unpack a list or dict when calling a function.

    BeginnerIn-depth3 min read
  2. What are mutable and immutable objects in Python, and why is a mutable default argument a bug?

    Mutable objects such as lists, dicts and sets can change in place; immutable ones such as int, str and tuple cannot. Default arguments are evaluated once, when the function is defined, so a list used as a default is shared across every call. Use None as the default and create the list inside the function.

    BeginnerIn-depth3 min read
  3. What is the difference between a list and a tuple in Python?

    A list is mutable, so you can add, remove or change items after creating it. A tuple is immutable, so its contents are fixed once created. Tuples are slightly lighter and can be used as dictionary keys if all their items are hashable; lists cannot.

    BeginnerIn-depth3 min read
  4. What is the difference between a shallow copy and a deep copy in Python?

    A shallow copy creates a new outer container but keeps references to the same inner objects, so changing a nested list affects both. A deep copy recursively copies everything inside, so the two are fully independent. Use copy.copy() for shallow and copy.deepcopy() for deep.

    BeginnerIn-depth3 min read
  5. How does a dictionary work internally in Python, and why must keys be hashable?

    A dict is a hash table. Python calls hash() on the key to pick a slot, then uses == to confirm the match, which makes lookups O(1) on average. Keys must be hashable, meaning their hash never changes, otherwise the dict would look in the wrong slot and lose them. That is why lists cannot be keys but tuples of immutable values can.

    IntermediateIn-depth4 min read
  6. What is a decorator in Python and how do you write one?

    A decorator is a function that takes another function, wraps it with extra behaviour, and returns the wrapped version. Writing @my_decorator above a function is shorthand for func = my_decorator(func). They are used for logging, timing, caching and access checks without changing the original function's code.

    IntermediateIn-depth3 min read
  7. What is a generator in Python, and how is yield different from return?

    A generator is a function that uses yield to produce values one at a time, pausing after each one and resuming where it left off on the next request. return ends the function and gives back one result, while yield hands out a value and keeps the function's state. Generators save memory because they never build the full list.

    IntermediateIn-depth3 min read
  8. What is the GIL in Python, and when should you use threads versus multiprocessing?

    The Global Interpreter Lock in CPython lets only one thread run Python bytecode at a time, so threads do not speed up CPU-heavy pure Python code. Threads still work well for I/O-bound work, because the lock is released while waiting. For CPU-bound work, use multiprocessing. Python 3.13 added an optional, experimental free-threaded build without the GIL.

    AdvancedIn-depth5 min read
  9. Are strings mutable in Python, and how do you change a character in one?

    Strings are immutable, so s[0] = "x" raises TypeError. To change one, build a new string using slicing, replace(), or join over a list of characters.

    BeginnerQuick answer1 min read
  10. How do dictionary and set comprehensions work in Python?

    A dict comprehension uses curly braces with key: value, as in {k: v for ...}. A set comprehension uses curly braces with one expression, as in {x for ...}, and removes duplicates automatically.

    BeginnerQuick answer1 min read
  11. How do try, except, else and finally work together in Python?

    try holds the risky code, except handles an error, else runs only if no exception occurred, and finally always runs, whether or not there was an error. Use else for code that depends on the try succeeding.

    BeginnerQuick answer1 min read
  12. How do you create and raise a custom exception in Python?

    Subclass Exception (not BaseException), give it a clear name ending in Error, and raise it with raise. Add attributes or a message in __init__ if callers need details. A shared base class lets callers catch a whole family.

    BeginnerQuick answer1 min read
  13. How do you merge two dictionaries in Python?

    Use d1 | d2 in Python 3.9+, or {**d1, **d2} in older versions, or d1.update(d2) to modify d1 in place. When both have the same key, the value from the right-hand dictionary wins.

    BeginnerQuick answer1 min read
  14. How do you read and write JSON in Python?

    Use the json module: json.dumps and json.loads convert between Python objects and JSON strings, while json.dump and json.load do the same with file objects. JSON null becomes None, and keys always become strings.

    BeginnerQuick answer1 min read
  15. How do you swap two variables in Python without a temporary variable?

    Use tuple unpacking: a, b = b, a. The right side is evaluated into a tuple first, then assigned to the names on the left, so no temporary variable is needed.

    BeginnerQuick answer1 min read
  16. How does string slicing work in Python, and what do negative indices mean?

    s[start:stop:step] takes characters from start up to but not including stop. Negative indices count from the end, so s[-1] is the last character. Out-of-range slice bounds are clamped and never raise an error.

    BeginnerQuick answer1 min read
  17. In a list comprehension, where does the if go: before or after the for?

    A filter if goes after the for clause and drops items. An if-else that chooses between two values is an expression, so it goes before the for. Writing else after the for is a SyntaxError.

    BeginnerQuick answer1 min read
  18. Is Python statically or dynamically typed, and is it strongly or weakly typed?

    Python is dynamically typed, because types are checked at runtime and a name can point to any object. It is also strongly typed, because it will not silently mix incompatible types, so "5" + 5 raises TypeError.

    BeginnerQuick answer1 min read
  19. Is there a maximum value for an int in Python?

    No. Python 3 integers have arbitrary precision: they grow to use as much memory as the value needs, so they never overflow. sys.maxsize is only the largest index a container can have, not the largest int. Floats, by contrast, are 64-bit and do overflow to inf.

    BeginnerQuick answer1 min read
  20. What are the common file modes in Python's open() function?

    r" reads (default), "w" writes and erases existing content, "a" appends to the end, and "x" creates a new file and fails if it exists. Adding "+" allows both read and write, and "b" means binary instead of text.

    BeginnerQuick answer1 min read
  21. What are the common set operations in Python, and what is a frozenset?

    Sets support union (|), intersection (&), difference (-) and symmetric difference (^). A set holds unique, hashable items with fast membership tests. A frozenset is an immutable set, so it can be a dict key or a set element.

    BeginnerQuick answer1 min read
  22. What are the different ways to format strings in Python, and which should you prefer?

    Python has % formatting, str.format() and f-strings. Prefer f-strings (3.6+): they are the most readable and usually the fastest, because expressions are written directly inside the string.

    BeginnerQuick answer1 min read
  23. What are the main built-in data types in Python?

    Numbers (int, float, complex, bool), text (str), sequences (list, tuple, range), mappings (dict), sets (set, frozenset), bytes types and NoneType. Lists, dicts and sets are mutable; the rest are immutable.

    BeginnerQuick answer1 min read
  24. What are truthy and falsy values in Python?

    Every object has a truth value when used in an if or while. Falsy values are False, None, zero of any numeric type, and empty containers such as '', [], (), {}, set() and range(0). Everything else is truthy unless its class defines __bool__ or __len__ to say otherwise.

    BeginnerQuick answer1 min read
  25. What does if __name__ == "__main__" do in a Python script?

    When a file runs directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name instead. The if-check lets a file run some code only when executed as a script, not when imported.

    BeginnerQuick answer1 min read
  26. What does range() return in Python 3, and is it a list?

    range() returns a lazy range object, not a list. It stores only start, stop and step, so range(10**9) takes tiny memory, supports indexing, len() and the in operator, and produces numbers only when asked.

    BeginnerQuick answer1 min read
  27. What does the assert statement do, and when should you not use it?

    assert condition, message raises AssertionError if the condition is false. It is for internal sanity checks during development. Do not use it to validate user input, because assertions are removed when Python runs with the -O flag.

    BeginnerQuick answer1 min read
  28. What is a lambda function in Python, and what are its limits?

    A lambda is a small anonymous function written as lambda args: expression. It contains a single expression, returns its value automatically and cannot hold statements. It is handy as a short key or callback.

    BeginnerQuick answer1 min read
  29. What is a list comprehension in Python, and when should you use one?

    A list comprehension builds a list in one expression: [expr for item in iterable if condition]. It is shorter and usually faster than an append loop. Use it for simple transform-and-filter work, not for complicated logic.

    BeginnerQuick answer1 min read
  30. What is None in Python and how is it different from 0, False or an empty string?

    None is a special singleton object of type NoneType that means no value. It is falsy like 0, False and '', but it is not equal to any of them. Functions without a return statement return None, and you should test for it with is None.

    BeginnerQuick answer1 min read