9. Important Distinctions

Key differences that trip people up; know them to avoid subtle bugs.

Question: What is the difference between is and ==?

Answer:

  • == (Equality): Checks if the values of two objects are the same.

  • is (Identity): Checks if two variables point to the exact same object in memory.

Example: a = [1]; b = [1]. Here, a == b is True, but a is b is False.

Question: What is EAFP vs LBYL?

Answer: EAFP (Easier to Ask Forgiveness than Permission) tries an operation and handles exceptions; LBYL (Look Before You Leap) checks conditions first.

# EAFP
try:
    value = d[key]
except KeyError:
    value = default

# LBYL
value = d[key] if key in d else default

Explanation: EAFP is idiomatic in Python and thread-safe for races; LBYL can be clearer for simple checks.

Question: What is the difference between an iterable and an iterator?

Answer:

  • An iterable is an object you can loop over (like a list). It has an __iter__ method that returns an iterator.

  • An iterator is the object that does the actual iterating. It has a __next__ method that returns the next item and raises StopIteration when finished.

Question: What's the difference between threading, multiprocessing, and asyncio?

Answer: They are all tools for concurrency, but for different use cases:

  • threading: Good for I/O-bound tasks (e.g., network, disk). Limited for CPU-bound work due to the GIL allowing only one thread to run Python bytecode at a time.

  • multiprocessing: Best for CPU-bound tasks; runs multiple processes in parallel and sidesteps the GIL.

  • asyncio: Scales many concurrent I/O tasks on a single thread using non-blocking I/O and await.

Question: What is the difference between assignment and copying?

Answer: a = b makes two names point to the same object; copy.copy makes a shallow copy; copy.deepcopy recursively copies nested objects.

Question: Which built-in types are mutable vs immutable?

Answer: Immutable: int, float, bool, str, tuple, frozenset, bytes. Mutable: list, dict, set, bytearray. Mutability affects hashing and use as dict keys.