Python Semantics and Web Protocol Fundamentals

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

During a software engineering technical screen, walk through the following four foundational language and web-platform topics clearly enough that a teammate could apply the rules without hitting subtle production bugs:

  1. Mutable vs. immutable sequences in Python: How do list and tuple differ in behavior and runtime properties, and how do you decide which one fits a given situation?
  2. Identity vs. value comparison in Python: How does is differ from ==, and where should each operator be used in real code?
  3. Cleartext vs. encrypted web transport: How does HTTPS build upon plain HTTP, and what concrete security guarantees does it add over an untrusted network?
  4. Service contracts and resource lifecycle: What do the acronyms API and CRUD stand for, and how does a typical HTTP web service expose CRUD actions on a domain resource?

Scope & Expectations

  • Explain the underlying mechanics—not just one-line definitions—connecting mutability to dictionary keys, object references to equality semantics, and transport security to server identity.
  • Highlight practical edge cases (such as nested mutable items, small-integer caching, or network retries) with concise, illustrative examples.
  • Show how HTTP methods, URL paths, and response status codes express resource operations cleanly and predictably.

Step-by-step walkthrough

  1. list vs tuple: mutability and why it matters

    Both list and tuple are ordered sequences in Python that can hold items of any type, support indexing (seq[0]), slicing (seq[1:3]), len(), in, and for loops. Their core difference is mutability — whether an object's contents can be changed in place after it is created:

    • A list is mutable: you can add, remove, reorder, or replace elements in place (xs.append(4), xs.pop(), xs.sort(), xs[0] = 99).
    • A tuple is immutable: once created, its length and element slots are locked. It exposes only read-only methods (count and index), and t[0] = 99 raises TypeError.

    Three practical consequences follow directly from mutability:

    1. Hashability (usable as dict keys and set members). Hashability means an object has a fixed integer hash value (hash(obj)) over its entire lifetime so a hash table (dict or set) can always find the bucket where it was stored. A tuple is hashable as long as every item inside it is also hashable. A list is never hashable: if you mutated a list after using it as a dictionary key, its hash would change and the dictionary would look in the wrong bucket.
    2. Memory footprint. Because a list can grow, CPython stores the list header separately from a dynamically resized pointer array with spare capacity. A tuple's size never changes, so CPython packs its element pointers directly inside a single fixed-size object. On 64-bit CPython 3.13, [1, 2, 3] takes 88 bytes while (1, 2, 3) takes 64 bytes (not counting the integer objects themselves).
    3. Compile-time constant folding. CPython prebuilds a tuple of literal constants like (1, 2, 3) once at compile time and reuses it, whereas [1, 2, 3] must allocate a fresh list object every time the line runs so mutating one run's list cannot corrupt the next run.
    Why a mutable list cannot be a dict key:
      insert key (3, 4) -> hash((3, 4)) puts value in bucket #5 -> lookup (3, 4) checks bucket #5 (found!)
      if [3, 4] were allowed and mutated to [3, 9]:
        stored in bucket #5, but lookup now computes hash([3, 9]) -> checks bucket #2 (lost!)
    
    import sys
    
    point = (3, 4)
    distances = {point: 5.0}          # valid: tuple of ints is hashable
    
    try:
        bad_dict = {[3, 4]: 5.0}      # fails immediately
    except TypeError as exc:
        print(exc)                    # unhashable type: 'list'
    
    print(sys.getsizeof([1, 2, 3]))   # 88 bytes on 64-bit CPython 3.13
    print(sys.getsizeof((1, 2, 3)))   # 64 bytes on 64-bit CPython 3.13
    
  2. When to choose list vs tuple, and two classic traps

    Choose between them based on whether the collection can grow/change and what the positions mean:

    • Use a list for a variable-length collection of similar items that changes over time: lines read from a file, search results, or active tasks in a queue.
    • Use a tuple for a fixed-size record where each position has a specific role, or whenever you need a hashable key or write-protection:
      • coordinates (x, y) or an RGB color (255, 128, 0),
      • returning multiple values from a function (return mean, stdev packs a 2-tuple),
      • composite dictionary keys like (user_id, date),
      • fixed configuration constants you want protected from accidental edits. (When positional indices like row[2] hurt readability, typing.NamedTuple or @dataclass(frozen=True) gives named fields while keeping immutability.)

    Watch out for two classic tuple traps in interviews:

    • One-element tuple syntax: (1) is just the integer 1 in math parentheses. A single-element tuple requires a trailing comma: (1,).
    • Shallow immutability: Shallow immutability means a tuple only locks which object references sit in its slots; if one of those objects is itself mutable (like a list), that inner object can still be modified in place. Such a tuple is also unhashable (hash(([1],)) raises TypeError). Even trickier, t = ([1],); t[0] += [2] both mutates the inner list and raises TypeError, because Python executes += in two steps: first list.__iadd__ appends 2 in place, and second Python tries to assign the result back into t[0].
    single_int = (1)
    single_tuple = (1,)
    print(type(single_int), type(single_tuple))  # <class 'int'> <class 'tuple'>
    
    t = ([1],)
    try:
        # Step 1: t[0].__iadd__([2]) mutates the inner list to [1, 2] in place.
        # Step 2: t[0] = result tries to assign into the tuple and raises TypeError.
        t[0] += [2]
    except TypeError:
        pass
    
    print(t)  # ([1, 2],) -> the inner list already changed before TypeError fired!
    
  3. is vs ==: object identity vs value equality

    Python separates whether two variables point to the exact same object in memory from whether two objects contain equivalent values:

    • a == b tests value equality. Python calls a.__eq__(b), which compares contents according to the type's rules (and can be customized by classes).
    • a is b tests object identity. It checks whether a and b refer to the exact same object in memory (equivalent to id(a) == id(b) while both objects are alive) and cannot be overridden.
    a = [1, 2]      b = [1, 2]      c = a
    
      a ---+                          b ---> [1, 2]  (object at 0x1002)
           |---> [1, 2]  (object at 0x1001)
      c ---+
    
      a == b  -> True   (both lists hold 1, then 2)
      a is b  -> False  (two distinct list objects in memory)
      a is c  -> True   (both names point to object 0x1001)
      1 == 1.0 -> True  (numeric equality across int and float)
      1 is 1.0 -> False (an int object is never a float object)
    

    Rule of thumb: Use is (and is not) only for singletons — objects guaranteed to have only one instance in the program, such as x is None, x is not None, or a custom sentinel (MISSING = object()). Always use == to compare numbers, strings, lists, dicts, or tuples.

    Why casual testing misleads beginners: CPython interns (caches) small integers from -5 through 256 in a shared array at startup. As a result, int("256") is int("256") evaluates to True, whereas int("257") is int("257") evaluates to False. Relying on is for values causes silent bugs depending on magnitude or Python implementation.

    Two real-world cases where is and == diverge sharply:

    # 1. IEEE-754 NaN ("Not a Number") is never equal to anything, even itself:
    nan = float("nan")
    print(nan == nan)                       # False
    print(nan in [nan])                     # True: list 'in' checks 'item is target' before '=='
    print(float("nan") in [float("nan")])   # False: two separate NaN objects, and == is False
    
    # 2. Custom __eq__ does not even have to return a single bool (e.g., NumPy arrays):
    import numpy as np
    arr1 = np.array([1, 2])
    arr2 = np.array([1, 2])
    print(arr1 == arr2)                     # [ True  True ] (an element-wise boolean array)
    
  4. HTTP vs HTTPS: what TLS adds on the wire

    HTTP (Hypertext Transfer Protocol) is the application-level request/response language of the web: a client sends a method (GET, POST), path (/account), headers, and optional body; the server replies with a numeric status code (200, 404), headers, and body. Plain HTTP sends all of these bytes in cleartext (default TCP port 80), so anyone along the network path — café Wi-Fi, a router, an ISP, or an untrusted proxy — can read or silently alter passwords, session cookies, and page contents.

    HTTPS runs that exact same HTTP protocol inside a TLS (Transport Layer Security, the successor to SSL) tunnel, over default port 443. TLS adds three security guarantees:

    1. Confidentiality (encryption): Symmetric cipher keys negotiated during the connection scramble the HTTP request and response so eavesdroppers cannot read them.
    2. Integrity (tamper detection): Cryptographic message authentication tags accompany every record; if an attacker flips even one bit in transit, verification fails and the connection aborts.
    3. Server authentication (identity proof): The server presents a digital certificate signed by a trusted Certificate Authority (CA) — an organization pre-trusted by your operating system or browser to verify domain ownership. The client checks that the signature chain is valid, the certificate has not expired, and the certificate's domain matches the hostname you requested. Without authentication, encryption alone would happily establish a private encrypted tunnel directly to an impostor (a man-in-the-middle attack).
    Example: client on public Wi-Fi requests GET https://bank.example/account?id=42
             with header Cookie: session=8f3a...
    
    Over plain HTTP (port 80):
      Wi-Fi observer sees & can edit: host, "/account?id=42", Cookie "8f3a...", HTML response
    
    Over HTTPS (port 443):
      Wi-Fi observer STILL sees: client & server IPs, port 443, packet timing & approximate sizes,
                                 and hostname "bank.example" in TLS's SNI (Server Name Indication)
                                 handshake field (unless Encrypted Client Hello is enabled)
      Encrypted inside TLS:      full path "/account?id=42", headers, session cookie, request/response body
    
    import ssl
    
    # Python's default TLS context enforces both certificate-chain trust and hostname matching:
    ctx = ssl.create_default_context()
    print(ctx.verify_mode == ssl.CERT_REQUIRED)  # True: untrusted/self-signed certs are rejected
    print(ctx.check_hostname)                    # True: cert domain must match requested host
    
  5. HTTPS in practice: latency, HSTS, and what the padlock does NOT mean

    Interviewers often ask about the practical cost and limits of HTTPS:

    • Connection setup latency: Before sending the first HTTP byte, client and server run a TLS handshake to verify the certificate and agree on encryption keys. In TLS 1.3, this adds 1 network round-trip time (RTT) — one back-and-forth message pair — on top of the TCP handshake (down from 2 RTTs in TLS 1.2).
    • Forward secrecy: TLS 1.3 uses ephemeral key exchange (fresh temporary math keys per session), which provides forward secrecy — even if someone steals the server's long-term private certificate key next year, they still cannot decrypt traffic they recorded today.
    • HSTS (Strict-Transport-Security): If a user types bank.example without https://, their first request might go out over plain HTTP and get hijacked before a redirect. HSTS is an HTTP response header telling the browser to automatically upgrade all future visits to HTTPS before sending a single packet (and browser HSTS preload lists protect the very first visit too). Cookies marked Secure are likewise restricted so browsers never send them over plain HTTP.
    • What HTTPS does NOT guarantee: A valid TLS certificate only proves that the server you reached controls that domain. A phishing domain like bank-login-help.example can obtain a valid free certificate in seconds, and HTTPS does not protect your data if the server itself is breached after decryption.
  6. API and CRUD: core concepts

    An API (Application Programming Interface) is the explicit contract one piece of software exposes so other software can use it without knowing its internal implementation. An API specifies what operations exist, what inputs they expect, what outputs they return, and what errors they raise. In-process, list.append(x) is part of Python's standard-library API; over a network, a web API exposes operations over HTTP (commonly exchanging JSON).

    CRUD stands for the four foundational lifecycle operations on persistent data:

    • C — Create: add a new record (SQL INSERT),
    • R — Read: fetch one record or list matching records (SQL SELECT),
    • U — Update: modify an existing record (SQL UPDATE),
    • D — Delete: remove a record (SQL DELETE).
  7. Mapping CRUD to HTTP in a REST web service

    In a REST (Representational State Transfer) web API, you model domain entities as resources named by noun URLs (like /books and /books/17), use the HTTP method to express the CRUD action, and use HTTP status codes to report the outcome:

    CRUD Action   HTTP Method + URL   Meaning & Typical Success Status
    Create        POST   /books       Create a new book -> 201 Created (returns created book + Location)
    Read (list)   GET    /books       List books (with ?limit=20&author=...) -> 200 OK
    Read (one)    GET    /books/17    Fetch book 17 -> 200 OK (or 404 Not Found)
    Update (full) PUT    /books/17    Replace the entire book 17 record -> 200 OK or 204 No Content
    Update (part) PATCH  /books/17    Modify only the provided fields -> 200 OK or 204 No Content
    Delete        DELETE /books/17    Remove book 17 -> 204 No Content (or 404 Not Found)
    

    Common client/server status codes include 400 Bad Request (invalid input), 401 Unauthorized (missing/bad login), 403 Forbidden (logged in, not permitted), 404 Not Found, 409 Conflict (duplicate), and 500 / 503 (server errors).

    Two HTTP method guarantees govern automatic network retries:

    • Safe methods (GET, HEAD, OPTIONS) are read-only — calling them never asks the server to change state.
    • Idempotent methods produce the exact same server state whether an identical request arrives once or five times. GET, PUT, and DELETE are idempotent; POST is not (retrying POST /books after a timeout can create two duplicate books!), and PATCH is only idempotent if the patch sets values rather than incrementing a counter. Note that idempotency is about stored server state, not status codes: calling DELETE /books/1 twice returns 204 first and 404 second, yet the server state after one call and two calls is identical (book 1 is gone).
    books = {}
    next_id = 1
    
    
    def handle_books_request(method, path, body=None):
        """Minimal in-memory REST router returning (status_code, response_body)."""
        global next_id
        parts = path.strip("/").split("/")  # "/books/1" -> ["books", "1"]
        if parts[0] != "books" or len(parts) > 2:
            return 404, {"error": "route not found"}
    
        # Collection endpoint: /books
        if len(parts) == 1:
            if method == "GET":
                return 200, list(books.values())
            if method == "POST":
                book = {"id": next_id, "title": body["title"], "pages": body["pages"]}
                books[next_id] = book
                next_id += 1
                return 201, book
            return 405, {"error": "method not allowed"}
    
        # Item endpoint: /books/<id>
        if not parts[1].isdigit():
            return 400, {"error": "book id must be an integer"}
        book_id = int(parts[1])
        if book_id not in books:
            return 404, {"error": "book not found"}
    
        if method == "GET":
            return 200, books[book_id]
        if method == "PUT":
            # PUT replaces the full resource representation
            books[book_id] = {"id": book_id, "title": body["title"], "pages": body["pages"]}
            return 200, books[book_id]
        if method == "PATCH":
            # PATCH updates only the fields supplied in body
            books[book_id].update({k: v for k, v in body.items() if k != "id"})
            return 200, books[book_id]
        if method == "DELETE":
            del books[book_id]
            return 204, None
        return 405, {"error": "method not allowed"}
    
    POST   /books   {"title": "Dune", "pages": 412}          -> 201 {"id": 1, "title": "Dune", "pages": 412}
    GET    /books/1                                          -> 200 {"id": 1, "title": "Dune", "pages": 412}
    PATCH  /books/1 {"pages": 416}                           -> 200 {"id": 1, "title": "Dune", "pages": 416}
    PUT    /books/1 {"title": "Dune Messiah", "pages": 256}  -> 200 {"id": 1, "title": "Dune Messiah", "pages": 256}
    DELETE /books/1                                          -> 204 None
    DELETE /books/1                                          -> 404 {"error": "book not found"}  (state unchanged: idempotent)
    

    Not every web service uses RESTful HTTP verbs: GraphQL sends queries (reads) and mutations (writes) typically over POST /graphql, and gRPC calls strongly typed remote procedures like CreateBook or GetBook over HTTP/2. The underlying CRUD operations remain the same; only how they are mapped onto the transport changes.

Intuition & how it works

Think of all four questions as testing one unifying engineering skill: knowing what guarantees a tool actually gives you. In Python, choosing tuple over list is a guarantee about mutability (whether contents can change in place), and choosing is vs == is choosing between same physical object vs equivalent contents. On the web, choosing HTTPS over HTTP adds transport security guarantees (privacy, tamper detection, and verified server identity), while RESTful CRUD APIs establish predictable state-change contracts between clients and servers.

A surface-level answer falls short when it stops at slogans — like saying "tuples are faster lists", "is checks if two things are the same", or "HTTPS encrypts HTTP". Those shortcuts miss why the distinction breaks real production code: mutating a key breaks dictionary hash lookups, small-integer caching makes a is b appear to work in local tests and fail on 257, encryption without certificate verification still lets an impostor intercept passwords, and retrying a non-idempotent POST charges a customer twice.

Walk through one tiny end-to-end example tying all four concepts together:

  1. list vs tuple: You store daily coordinates visited by a user in a list (visits = [(3, 4), (5, 6)]) because the history grows with visits.append((7, 8)), while each coordinate (3, 4) is a fixed 2-item tuple so it can serve as a dictionary key (grid_cache[(3, 4)] = "park").
  2. is vs ==: When checking cached = grid_cache.get((9, 9)), you test if cached is None: (identity with the single None object), whereas when comparing user input [3, 4] against [3, 4] you use == (value equality across two distinct objects).
  3. HTTP vs HTTPS: Sending Cookie: session=abc to https://api.example.com/books wraps the HTTP request in a TLS (Transport Layer Security) tunnel that verifies api.example.com's certificate, blocks tampering, and hides the URL path, headers, and JSON body from Wi-Fi snoopers.
  4. API & CRUD: Inside that tunnel, POST /books creates book 1 (201 Created), GET /books/1 reads it (200 OK), PATCH /books/1 updates one field, PUT /books/1 replaces the whole book, and DELETE /books/1 removes it (204 No Content).

Key points

  • list vs tuple: A list is mutable (modifiable in place); a tuple is immutable (its element slots cannot be reassigned). Because of immutability, a tuple containing only hashable (fixed-hash) elements is itself hashable (dict key / set member), uses less memory (64 vs 88 bytes for 3 items on 64-bit CPython 3.13), and can be prebuilt at compile time when made of literals. Remember that tuple immutability is shallow: a mutable list inside a tuple (([1],)) can still change in place.
  • is vs ==: is compares object identity (same memory object; id(a) == id(b)), whereas == compares value equality via __eq__. Reserve is / is not for singletons (None and custom sentinel objects) and use == for numbers, strings, and containers — never trust is on integers just because CPython caches -5 through 256.
  • HTTP vs HTTPS: HTTPS is standard HTTP carried inside a TLS tunnel (port 443 instead of 80). TLS provides confidentiality (encryption), integrity (tamper detection), and server authentication (certificate chain signed by a trusted Certificate Authority and matched to the hostname). Network observers can still see IP addresses, port 443, approximate payload sizes, and usually the domain name in the TLS handshake's SNI (Server Name Indication) field.
  • API and CRUD: An API (Application Programming Interface) is a defined software contract of operations, inputs, outputs, and errors; CRUD stands for Create, Read, Update, Delete. In REST over HTTP: POST creates (201), GET reads (200/404), PUT replaces in full, PATCH updates partially, and DELETE removes (204). GET, PUT, and DELETE are idempotent (repeating the call leaves the server in the same state as calling it once); POST is not.

Common mistakes

  • Saying tuples are "just faster, read-only lists" without connecting immutability to hashability (why (x, y) works as a dict key and [x, y] raises TypeError).
  • Claiming every tuple is hashable — hash((1, [2])) raises TypeError: unhashable type: 'list' because the inner list can mutate.
  • Writing (1) instead of (1,) for a one-element tuple ((1) evaluates to the integer 1).
  • Using is to compare strings or numbers because it happened to return True on cached small ints (-5..256) or interned identifier strings, or writing x == None instead of x is None (a custom __eq__ method can override == or raise an error, as NumPy arrays do).
  • Defining HTTPS solely as "encrypted HTTP" and forgetting server authentication — encrypting traffic to an unverified attacker's key offers zero protection against man-in-the-middle interception.
  • Assuming the browser padlock means a website is trustworthy (phishing domains easily obtain valid certificates) or hides which domain you visited from your ISP.
  • Conflating PUT (replace entire resource) with PATCH (partial modification), or thinking idempotent means "every retry returns the exact same status code" rather than "every retry leaves the server in the same stored state" (a second DELETE /books/1 may return 404 instead of 204 and is still idempotent).

Follow-up questions

  • Why do Python dictionary keys have to be hashable, and what goes wrong if a key mutates after insertion? A Python dict is a hash table — an array of slots where hash(key) determines which slot to probe first, followed by == to confirm an exact key match. If you could insert a list [3, 4] into slot 5 and then append 5 so the key became [3, 4, 5], its hash would now point to a completely different slot; d[[3, 4, 5]] would look in the wrong slot and miss it, while d[[3, 4]] would fail the == check. That is why mutable built-ins (list, dict, set) set __hash__ = None, while immutable built-ins (int, str, frozenset, and tuples of hashable items) implement __hash__.

  • How can a backend API make retrying a POST request safe when the client hits a network timeout? When a client sends POST /orders and the network drops before the response arrives, the client cannot tell whether the server created the order or never received the packet. The standard fix is an idempotency key — a unique client-generated UUID sent in a header such as Idempotency-Key: 7c1e.... The server stores that key alongside the created order and response inside the same database transaction; if the client retries with the same key, the server recognizes it, skips creating a duplicate order, and replays the stored 201 Created response.

text Attempt 1: POST /orders Idempotency-Key: 7c1e... -> creates order #55, saves response under 7c1e... (network drops!) Retry 2: POST /orders Idempotency-Key: 7c1e... -> finds 7c1e..., skips insert, returns saved 201 for order #55

  • What happens step by step on the network when a browser visits an HTTPS URL for the first time? First, the browser resolves example.com to an IP address via DNS (Domain Name System) and opens a connection to port 443 (TCP for HTTP/1.1 and HTTP/2, or UDP-based QUIC for HTTP/3). Next, it runs the TLS handshake: the browser sends its supported cipher suites, ephemeral key share, and the target domain (SNI), and the server replies with its key share, its digital certificate chain, and a cryptographic signature proving it holds the certificate's private key. After the browser verifies that a trusted Certificate Authority signed the chain, the dates are valid, and the certificate covers example.com, both sides derive shared symmetric session keys and send the encrypted GET /books request and 200 OK response.

Follow-up questions

Similar questions

More Pilot interview questions

All 2 Pilot questions →