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:
- Mutable vs. immutable sequences in Python: How do
listandtuplediffer in behavior and runtime properties, and how do you decide which one fits a given situation? - Identity vs. value comparison in Python: How does
isdiffer from==, and where should each operator be used in real code? - Cleartext vs. encrypted web transport: How does HTTPS build upon plain HTTP, and what concrete security guarantees does it add over an untrusted network?
- Service contracts and resource lifecycle: What do the acronyms
APIandCRUDstand 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
list vs tuple: mutability and why it matters
Both
listandtupleare ordered sequences in Python that can hold items of any type, support indexing (seq[0]), slicing (seq[1:3]),len(),in, andforloops. Their core difference is mutability — whether an object's contents can be changed in place after it is created:- A
listis mutable: you can add, remove, reorder, or replace elements in place (xs.append(4),xs.pop(),xs.sort(),xs[0] = 99). - A
tupleis immutable: once created, its length and element slots are locked. It exposes only read-only methods (countandindex), andt[0] = 99raisesTypeError.
Three practical consequences follow directly from mutability:
- Hashability (usable as
dictkeys andsetmembers). Hashability means an object has a fixed integer hash value (hash(obj)) over its entire lifetime so a hash table (dictorset) can always find the bucket where it was stored. Atupleis hashable as long as every item inside it is also hashable. Alistis 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. - 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). - 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- A
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
listfor 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
tuplefor 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, stdevpacks 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.NamedTupleor@dataclass(frozen=True)gives named fields while keeping immutability.)
- coordinates
Watch out for two classic tuple traps in interviews:
- One-element tuple syntax:
(1)is just the integer1in 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],))raisesTypeError). Even trickier,t = ([1],); t[0] += [2]both mutates the inner list and raisesTypeError, because Python executes+=in two steps: firstlist.__iadd__appends2in place, and second Python tries to assign the result back intot[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!- Use a
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 == btests value equality. Python callsa.__eq__(b), which compares contents according to the type's rules (and can be customized by classes).a is btests object identity. It checks whetheraandbrefer to the exact same object in memory (equivalent toid(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(andis not) only for singletons — objects guaranteed to have only one instance in the program, such asx 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
-5through256in a shared array at startup. As a result,int("256") is int("256")evaluates toTrue, whereasint("257") is int("257")evaluates toFalse. Relying onisfor values causes silent bugs depending on magnitude or Python implementation.Two real-world cases where
isand==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)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 port80), 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:- Confidentiality (encryption): Symmetric cipher keys negotiated during the connection scramble the HTTP request and response so eavesdroppers cannot read them.
- 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.
- 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 bodyimport 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 hostHTTPS 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 typesbank.examplewithouthttps://, 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 markedSecureare 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.examplecan obtain a valid free certificate in seconds, and HTTPS does not protect your data if the server itself is breached after decryption.
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).
- C — Create: add a new record (SQL
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
/booksand/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), and500/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, andDELETEare idempotent;POSTis not (retryingPOST /booksafter a timeout can create two duplicate books!), andPATCHis only idempotent if the patch sets values rather than incrementing a counter. Note that idempotency is about stored server state, not status codes: callingDELETE /books/1twice returns204first and404second, yet the server state after one call and two calls is identical (book1is 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 likeCreateBookorGetBookover HTTP/2. The underlying CRUD operations remain the same; only how they are mapped onto the transport changes.- Safe methods (
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:
listvstuple: You store daily coordinates visited by a user in alist(visits = [(3, 4), (5, 6)]) because the history grows withvisits.append((7, 8)), while each coordinate(3, 4)is a fixed 2-itemtupleso it can serve as a dictionary key (grid_cache[(3, 4)] = "park").isvs==: When checkingcached = grid_cache.get((9, 9)), you testif cached is None:(identity with the singleNoneobject), whereas when comparing user input[3, 4]against[3, 4]you use==(value equality across two distinct objects).- HTTP vs HTTPS: Sending
Cookie: session=abctohttps://api.example.com/bookswraps the HTTP request in a TLS (Transport Layer Security) tunnel that verifiesapi.example.com's certificate, blocks tampering, and hides the URL path, headers, and JSON body from Wi-Fi snoopers. - API & CRUD: Inside that tunnel,
POST /bookscreates book1(201 Created),GET /books/1reads it (200 OK),PATCH /books/1updates one field,PUT /books/1replaces the whole book, andDELETE /books/1removes it (204 No Content).
Key points
listvstuple: Alistis mutable (modifiable in place); atupleis immutable (its element slots cannot be reassigned). Because of immutability, a tuple containing only hashable (fixed-hash) elements is itself hashable (dictkey /setmember), uses less memory (64vs88bytes 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.isvs==:iscompares object identity (same memory object;id(a) == id(b)), whereas==compares value equality via__eq__. Reserveis/is notfor singletons (Noneand custom sentinel objects) and use==for numbers, strings, and containers — never trustison integers just because CPython caches-5through256.- HTTP vs HTTPS: HTTPS is standard HTTP carried inside a TLS tunnel (port
443instead of80). 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, port443, 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:
POSTcreates (201),GETreads (200/404),PUTreplaces in full,PATCHupdates partially, andDELETEremoves (204).GET,PUT, andDELETEare idempotent (repeating the call leaves the server in the same state as calling it once);POSTis not.
Common mistakes
- Saying tuples are "just faster, read-only lists" without connecting immutability to hashability (why
(x, y)works as adictkey and[x, y]raisesTypeError). - Claiming every tuple is hashable —
hash((1, [2]))raisesTypeError: unhashable type: 'list'because the inner list can mutate. - Writing
(1)instead of(1,)for a one-element tuple ((1)evaluates to the integer1). - Using
isto compare strings or numbers because it happened to returnTrueon cached small ints (-5..256) or interned identifier strings, or writingx == Noneinstead ofx 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) withPATCH(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 secondDELETE /books/1may return404instead of204and 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
dictis a hash table — an array of slots wherehash(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 append5so 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, whiled[[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 /ordersand 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 asIdempotency-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 stored201 Createdresponse.
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.comto an IP address via DNS (Domain Name System) and opens a connection to port443(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 coversexample.com, both sides derive shared symmetric session keys and send the encryptedGET /booksrequest and200 OKresponse.
Follow-up questions
- Why do Python dictionary keys have to be hashable, and what goes wrong if a key mutates after insertion?
- How can a backend API make retrying a POST request safe when the client hits a network timeout?
- What happens step by step on the network when a browser visits an HTTPS URL for the first time?
Similar questions
- Detect Anagrams Without Sorting
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager