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 is the difference between remove(), pop() and del for a list?

    remove(x) deletes the first item equal to x. pop(i) deletes the item at index i (default last) and returns it. del lst[i] or del lst[a:b] deletes by index or slice and returns nothing.

    BeginnerQuick answer1 min read
  2. What is the difference between type() and isinstance() in Python?

    type(x) returns the exact class of x, so comparing with == ignores inheritance. isinstance(x, C) is True if x is an instance of C or of any subclass of C, so it is the usual choice for type checks.

    BeginnerQuick answer1 min read
  3. What is the LEGB rule in Python?

    LEGB is the order in which Python looks up a name: Local, Enclosing (outer functions), Global (module), then Built-in. The first scope that contains the name wins, and if none do, Python raises NameError.

    BeginnerQuick answer1 min read
  4. Why do we use the with statement when working with files?

    with guarantees the file is closed when the block ends, even if an exception occurs. It works through a context manager, an object with __enter__ and __exit__ methods, so cleanup does not depend on remembering to call close().

    BeginnerQuick answer1 min read
  5. Why does 0.1 + 0.2 == 0.3 return False in Python, and how do you compare floats correctly?

    Floats are stored in binary, and 0.1 and 0.2 have no exact binary form, so their sum is 0.30000000000000004. Compare floats with math.isclose(), or use decimal.Decimal when exact decimal arithmetic is needed, such as for money.

    BeginnerQuick answer1 min read
  6. Why is (5) not a tuple in Python, and how do you create a one-element tuple?

    Parentheses alone only group an expression, so (5) is just the integer 5. The comma makes the tuple, so a one-element tuple is written (5,) or 5,. The empty tuple is ().

    BeginnerQuick answer1 min read
  7. Write a function that reverses a string in Python.

    The shortest way is slicing with a negative step: s[::-1]. You can also use "".join(reversed(s)). Both build a new string in O(n) time, since strings cannot be changed in place.

    BeginnerQuick answerCoding1 min read
  8. Write a function to check whether a string is a palindrome, ignoring case and non-letters.

    Clean the string by keeping only letters and digits in lowercase, then compare it with its reverse. This runs in O(n) time. A two-pointer version avoids the extra reversed copy.

    BeginnerQuick answerCoding1 min read
  9. Write a function to check whether two strings are anagrams of each other.

    Two strings are anagrams if they contain the same characters with the same counts. Compare Counter(a) with Counter(b) in O(n) time, or compare sorted(a) with sorted(b) in O(n log n) time.

    BeginnerQuick answerCoding1 min read
  10. Write a function to flatten a list of lists into a single list.

    For one level of nesting, use a nested comprehension: [x for row in rows for x in row]. For arbitrary depth, use recursion and check isinstance(item, list). The flat version is O(n) in the number of elements.

    BeginnerQuick answerCoding1 min read
  11. Write a function to remove duplicates from a list while keeping the original order.

    Walk through the list, keep a set of items already seen, and add an item to the result only if it is not in the set. This is O(n) time. Using set(lst) alone is fast but loses the order.

    BeginnerQuick answerCoding1 min read
  12. Write a generator that yields the first n Fibonacci numbers.

    Keep two variables a and b, yield a, then update them with a, b = b, a + b, repeating n times. The generator produces one value at a time, uses O(1) memory and does O(n) additions in total.

    BeginnerQuick answerCoding1 min read
  13. Does the loop variable of a list comprehension leak into the surrounding scope in Python 3?

    No. In Python 3 a comprehension has its own scope, so its loop variable does not leak. A normal for loop does leave its variable behind. In Python 2, list comprehensions did leak.

    IntermediateQuick answer1 min read
  14. How do you make your own class work with +, len() and indexing in Python?

    Implement the matching dunder methods: __add__ for +, __len__ for len(), and __getitem__ for obj[i]. Python translates the syntax into calls to these methods, so no inheritance from built-in types is needed.

    IntermediateQuick answer1 min read
  15. How do you read a very large file in Python without loading it all into memory?

    Iterate over the file object directly with for line in f. It reads one line at a time through a buffer, so memory use stays small. read() and readlines() load everything at once and can exhaust memory on big files.

    IntermediateQuick answer1 min read
  16. How do you write your own context manager in Python?

    Either write a class with __enter__ and __exit__ methods, or write a generator function decorated with @contextlib.contextmanager that yields once. Code before the yield is setup and code after it is cleanup, which should sit in a finally block.

    IntermediateQuick answer1 min read
  17. How does a for loop work under the hood in Python?

    A for loop calls iter() on the object to get an iterator, then repeatedly calls next() on it, running the body each time. When next() raises StopIteration, the loop ends quietly.

    IntermediateQuick answer1 min read
  18. How does Python find a module when you write import?

    Python checks sys.modules for an already-loaded copy, then searches the directories in sys.path in order: the script's folder, PYTHONPATH entries, the standard library and site-packages. The first match wins, which is why a local file can shadow a library.

    IntermediateQuick answer1 min read
  19. What are Decimal and Fraction in Python, and when would you use them instead of float?

    Decimal does exact base-10 arithmetic, which suits money. Fraction stores a ratio of two integers and gives exact results for things like 1/3. Both avoid the binary rounding errors of float, at the cost of speed.

    IntermediateQuick answer1 min read
  20. What do the / and * markers in a Python function signature mean?

    Parameters before / are positional-only, so callers cannot pass them by name. Parameters after a bare * are keyword-only, so callers must pass them by name. Both make an API clearer and safer to change.

    IntermediateQuick answer1 min read
  21. What does "from module import *" do, and what is __all__?

    import * brings every public name of a module into your namespace, which can silently overwrite existing names. A module can control what it exports by defining __all__, a list of names. Without __all__, names starting with an underscore are skipped.

    IntermediateQuick answer1 min read
  22. What does super() do in Python, and why call super().__init__()?

    super() returns a proxy that looks up methods on the next class in the MRO. Calling super().__init__() runs the parent's initialiser so the inherited setup is not skipped. If a child defines __init__ and does not call it, the parent's attributes are never created.

    IntermediateQuick answer1 min read
  23. What does the @property decorator do in Python?

    @property turns a method into a read-only attribute, so obj.area calls the method without parentheses. Adding @name.setter lets you validate or compute on assignment while callers still use plain attribute syntax.

    IntermediateQuick answer1 min read
  24. What is a closure in Python?

    A closure is an inner function that remembers variables from the enclosing function even after that outer function has finished. It is how Python implements function factories and decorators with private state.

    IntermediateQuick answer1 min read
  25. What is pathlib, and why is it preferred over os.path?

    pathlib represents file paths as objects, so you can join them with /, read their parts and read or write files through methods. It is more readable than string-based os.path calls and handles Windows and Linux separators for you.

    IntermediateQuick answer1 min read
  26. What is the difference between @classmethod, @staticmethod and an instance method?

    An instance method receives self, the object. A classmethod receives cls, the class, and is commonly used for alternative constructors. A staticmethod receives neither and is just a function living in the class namespace.

    IntermediateQuick answer1 min read
  27. What is the difference between a class attribute and an instance attribute, and what does this code print?

    A class attribute is shared by all instances. An instance attribute belongs to one object. Assigning through an instance, like a.count = 5, creates a new instance attribute that shadows the class one, but mutating a shared list changes it for everyone.

    IntermediateQuick answer1 min read
  28. What is the difference between absolute and relative imports in Python?

    An absolute import gives the full path from the project root, like from shop.billing import total. A relative import uses dots to start from the current package, like from .billing import total. Relative imports work only inside packages.

    IntermediateQuick answer1 min read
  29. What is the difference between EAFP and LBYL in Python?

    LBYL (look before you leap) checks conditions first, like if key in d. EAFP (easier to ask forgiveness than permission) just tries the operation and handles the exception. Python code usually prefers EAFP, especially where checking and acting could race.

    IntermediateQuick answer1 min read
  30. What is the difference between str and bytes in Python 3?

    str holds Unicode text, a sequence of characters. bytes holds raw 8-bit values. You encode a str to get bytes and decode bytes to get a str, and you must name the encoding, usually UTF-8.

    IntermediateQuick answer1 min read