CTCaliberTek
Interview Questions

Python Fundamentals Interview Questions and Answers

15 core Python questions: types, mutability, is vs ==, scope, arguments, comprehensions, copying, and exceptions.

  1. 1. What are Python's key features?

    Python is interpreted (compiled to bytecode and run by a virtual machine), dynamically typed, garbage collected, and supports several paradigms: procedural, object-oriented, and functional. It has a large standard library, readable indentation-based syntax, and a huge ecosystem of third-party packages.

  2. 2. What is the difference between a list, a tuple, a set, and a dictionary?

    A list is an ordered, mutable sequence. A tuple is an ordered, immutable sequence, so it can be used as a dictionary key if its items are hashable. A set is an unordered collection of unique hashable items with fast membership tests. A dictionary maps unique hashable keys to values and keeps insertion order (guaranteed since Python 3.7).

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

    Mutable objects (list, dict, set, most custom classes) can change in place. Immutable objects (int, float, str, tuple, frozenset, bytes) cannot, so every change creates a new object. This matters for function arguments, default values, and hashing.

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

    == compares values using __eq__. is checks whether two names refer to the exact same object in memory. Use is for singletons such as None (x is None), and == for everything else. Small integers and some strings may be cached, which makes is give confusing results on values.

  5. 5. What is the mutable default argument pitfall?

    Default values are evaluated once, when the function is defined, so a mutable default is shared across calls.

    def add_item(item, items=[]):     # bug
        items.append(item)
        return items
    
    def add_item_fixed(item, items=None):
        if items is None:
            items = []
        items.append(item)
        return items
  6. 6. What are *args and **kwargs?

    *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. In a call, the same symbols unpack a sequence or dictionary into arguments.

    def report(*args, **kwargs):
        print(args, kwargs)
    
    report(1, 2, mode='fast')   # (1, 2) {'mode': 'fast'}
  7. 7. Explain Python's scoping rules (LEGB).

    Names are looked up in order: Local (inside the function), Enclosing (outer functions), Global (module level), and Built-in. Assigning to a name inside a function makes it local unless you declare it global or nonlocal first.

  8. 8. What is a list comprehension, and how is it different from a generator expression?

    A list comprehension builds the whole list immediately: [x * x for x in range(5)]. A generator expression uses parentheses, produces items lazily one at a time, and uses almost no memory, but can be consumed only once. Use a generator expression when you only need to iterate, for example sum(x * x for x in numbers).

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

    A shallow copy creates a new container but shares the inner objects. A deep copy recursively copies everything. Use the copy module: copy.copy and copy.deepcopy.

    import copy
    a = [[1, 2], [3, 4]]
    b = copy.copy(a)
    c = copy.deepcopy(a)
    a[0].append(99)
    print(b[0])   # [1, 2, 99], shared
    print(c[0])   # [1, 2], independent
  10. 10. How does exception handling work in Python?

    Use try to run risky code, except to handle specific errors, else for code that should run only if nothing was raised, and finally for cleanup that always runs. Catch specific exceptions rather than a bare except, and use raise to signal errors or re-raise.

    try:
        value = int(text)
    except ValueError as error:
        print('not a number:', error)
    else:
        print('ok', value)
    finally:
        print('done')
  11. 11. What is the difference between a module, a package, and a library?

    A module is a single Python file. A package is a directory of modules (traditionally with an __init__.py file). A library is a general term for a collection of reusable code, usually distributed as one or more packages through PyPI and installed with pip.

  12. 12. What are virtual environments, and why use them?

    A virtual environment is an isolated Python installation with its own installed packages, so projects with different dependency versions do not conflict. Create one with python -m venv .venv, activate it, install with pip, and record dependencies in requirements.txt or pyproject.toml.

  13. 13. What is the difference between a function and a method?

    A function is defined with def at module level and called by name. A method is a function defined inside a class; when called on an instance, Python passes the instance automatically as the first argument, conventionally named self.

  14. 14. What are f-strings?

    Formatted string literals (Python 3.6 and newer) start with f and embed expressions in braces. They support format specifications and, from 3.8, a = suffix for debugging.

    name, price = 'tea', 3.5
    print(f'{name} costs {price:.2f}')   # tea costs 3.50
    print(f'{price=}')                    # price=3.5
  15. 15. What is the difference between append, extend, and insert on a list?

    append adds one element at the end. extend adds every element of an iterable at the end. insert adds one element at a given index and shifts the rest, which is O(n). Also note that + creates a new list, while extend and += modify the existing one.

Interview Tips

  • Always mention the time complexity of the operation you choose in a coding question.
  • Know the mutable default argument and shallow copy pitfalls; they appear in almost every Python interview.
  • Prefer clear, idiomatic code: comprehensions, enumerate, zip, and the standard library.