Interview Q&A · Python · 30 questions in this topic
Strings, Lists, Tuples, Sets & Dictionaries — Python Interview Q&A
The built-in containers and the questions that follow them everywhere: mutation, hashing, copying, comprehensions and the cost of each choice. Part of Strings, Lists, Tuples, Sets & Dictionaries · 375 questions in the Python bank.
What are strings in Python, and how are they represented internally?
Answer
A string (str) is an immutable sequence of Unicode characters. Internally, CPython stores strings as arrays of fixed-width code points, choosing the smallest representation (1, 2, or 4 bytes per character) that fits the string's content — an optimization called flexible string representation.
Since Python 3.3 (PEP 393), CPython no longer uses one-size-fits-all UTF-32 storage. A string containing only ASCII/Latin-1 characters uses 1 byte per character; one containing characters up to U+FFFF uses 2 bytes; anything beyond that (emoji, rare scripts) uses 4 bytes.
This is invisible to the programmer — you always just get correct Unicode behavior — but it matters when discussing memory efficiency of large text datasets.
Example
s = "hello" print(type(s)) # <class 'str'> print(len(s)) # 5 print(s[0], s[-1]) # 'h' 'o' -- indexing from front and back
💡 Mention immutability up front — it's the property that explains why every "modifying" string method (.upper(),.replace(), etc.) returns a new string instead of changing the original.
What is string slicing, and how does it work?
Answer
Slicing extracts a sub-sequence from a string (or any sequence) using sequence[start:stop:step]. start is inclusive, stop is exclusive, and step controls direction and stride; all three are optional.
Omitting start defaults to the beginning, omitting stop defaults to the end, and omitting step defaults to 1. Negative indices count from the end (-1 is the last character), and a negative step reverses direction — which is how the famous s[::-1] reversal idiom works. Slicing never raises an IndexError for out-of-range bounds; it just clips to what's available.
Example
s = "Interview" print(s[0:4]) # 'Inte' print(s[:4]) # 'Inte' (same as above) print(s[4:]) # 'rview' print(s[-4:]) # 'rview' (last 4 characters) print(s[::2]) # 'Itriw' (every 2nd character) print(s[::-1]) # 'weivretnI' (reversed) print(s[100:200]) # '' (out of range -> empty, no error)
💡 If asked to reverse a string live, s[::-1] is the expected idiomatic answer — but be ready to also explain the manual approach (loop or reversed(s) + "".join(.)) if the interviewer wants to see you reason about the underlying mechanics.
Why are strings immutable in Python?
Answer
Strings are immutable for performance, safety, and hashability: it lets Python cache and reuse (intern) identical strings, safely share them across threads without locking, and use strings as dictionary keys or set members.
If strings were mutable, using one as a dictionary key would be dangerous — modifying the string after insertion would change its hash, corrupting the dictionary's internal structure. Immutability also enables string interning: CPython automatically reuses the same object in memory for many identical short strings (especially identifier-like strings), reducing memory use.
Every operation that looks like it "modifies" a string —.upper(), +=,.replace() — actually builds and returns a brand-new string object.
Example
s = "hello" new_s = s.replace("h", "j") print(s) # 'hello' -- original untouched print(new_s) # 'jello' -- a new object a = "python" b = "python" print(a is b) # True in most cases -- interning reuses the same object
What are the most useful built-in string methods?
Answer
The methods interviewers expect fluency with are.split(),.join(),.strip(),.replace(),.find(),.startswith() /.endswith(), and the case methods.upper() /.lower().
.split() breaks a string into a list on a delimiter (whitespace by default);.join() does the reverse, gluing an iterable of strings together with a separator.strip() removes leading/trailing whitespace (or specified characters);.find() returns an index or -1 if not found, while.index() does the same but raises ValueError if missing.
Example
text = " Python, Java, C++ " print(text.strip()) # 'Python, Java, C++' print(text.strip().split(", ")) # ['Python', 'Java', 'C++'] print("-".join(["a", "b", "c"])) # 'a-b-c' print("hello world".replace("world", "there")) # 'hello there' print("hello".find("z")) # -1 (not found) print("report.pdf".endswith(".pdf")) # True
💡 Knowing.find() returns -1 instead of raising, while.index() raises ValueError, is a small detail that interviewers use to separate candidates who've actually used the methods from those who've only read about them.
What is the difference between f-strings,.format(), and % formatting?
Answer
All three embed values into strings, but f-strings (Python 3.6+) are the modern, preferred choice — they're the most readable and fastest at runtime because expressions are evaluated inline and compiled directly into the string.
Key points
- 1% formatting — Syntax: "%s is %d" % (name, age); Notes: Oldest, C-style, still seen in legacy code and logging
- 2.format() — Syntax: "{} is {}".format(name, age); Notes: More flexible than %, verbose
- 3f-strings — Syntax: f"{name} is {age}"; Notes: Modern default; supports inline expressions and = debugging
Example
name, age = "Ana", 30 print("%s is %d years old" % (name, age)) # % formatting print("{} is {} years old".format(name, age)) # .format() print(f"{name} is {age} years old") # f-string (preferred) print(f"{age=}") # f-string debug shortcut -> 'age=30' print(f"{3.14159:.2f}") # inline formatting -> '3.14'
💡 Mention the f"{value=}" debugging syntax (3.8+) — it's a small but recent-enough feature that signals you write modern Python day-to-day.
What are Python lists, and how are they different from arrays in other languages?
Answer
A list is an ordered, mutable, dynamically resizable collection that can hold items of mixed types. Unlike a C array or Java array, a Python list doesn't require a fixed size or a single element type up front.
Internally, a CPython list is implemented as a dynamic array of pointers to objects (not the objects themselves), which is why it can hold mixed types — each slot just references some object elsewhere in memory. To amortize the cost of resizing, CPython over-allocates extra capacity when a list grows, so append() is usually O(1) amortized rather than O(n).
Example
mixed = [1, "two", 3.0, [4, 5], {"six": 6}] mixed.append(True) print(mixed) # [1, 'two', 3.0, [4, 5], {'six': 6}, True] print(len(mixed)) # 6
💡 If the interviewer follows up with "so is a Python list a linked list or an array?" — the correct answer is a dynamic array (like ArrayList in Java or std::vector in C++), which is why indexing (lst[i]) is O(1) but inserting at the front is O(n).
What are the most commonly used list methods?
Answer
The core set is.append(),.extend(),.insert(),.remove(),.pop(),.sort(),.reverse(), and.index() — covering adding, removing, reordering, and searching.
.remove(value) deletes the first matching value (raises ValueError if absent);.pop(index) removes and returns the item at a position (defaults to the last item);.sort() mutates the list in place and returns None (a common gotcha — see Q52 for the sort() vs sorted() distinction).
Example
nums = [3, 1, 4, 1, 5] nums.append(9) # [3, 1, 4, 1, 5, 9] nums.insert(0, 100) # [100, 3, 1, 4, 1, 5, 9] nums.remove(1) # removes first '1' -> [100, 3, 4, 1, 5, 9] last = nums.pop() # last = 9, nums -> [100, 3, 4, 1, 5] nums.sort() # in place -> [1, 3, 4, 5, 100] print(nums.index(4)) # 2
💡 Point out that.pop() without an argument removes from the end (O(1)), while.pop(0) removes from the front (O(n), since every remaining element must shift) — a subtle but real performance difference.
What is the difference between append(), extend(), and insert()?
Answer
.append(x) adds a single item to the end.extend(iterable) adds every item from an iterable individually to the end.insert(i, x) adds a single item at a specific index.
The most common bug here is calling.append() when.extend() was intended, which nests a whole list inside another instead of flattening it.
Example
a = [1, 2, 3] a.append([4, 5]) print(a) # [1, 2, 3, [4, 5]] -- nested! probably not what was intended b = [1, 2, 3] b.extend([4, 5]) print(b) # [1, 2, 3, 4, 5] -- flattened, one level c = [1, 2, 3] c.insert(1, "x") print(c) # [1, 'x', 2, 3]
What are Python tuples, and why would you use one over a list?
Answer
A tuple is an ordered, immutable sequence. You reach for a tuple instead of a list when the data shouldn't change after creation, when you need a hashable sequence (e.g., a dict key), or to signal structural intent (a fixed-size record like coordinates).
Tuples are commonly used for heterogeneous, fixed-structure data (like (latitude, longitude)), while lists are typically used for homogeneous, variable-length collections. Because they're immutable, tuples are also slightly more memory-efficient and can be used as dictionary keys or set members (as long as everything inside them is itself immutable/hashable).
Example
point = (10.5, 20.3) # a fixed 2-item record coordinates_seen = {point} # legal -- tuples are hashable # Tuple unpacking, one of the most idiomatic tuple use cases x, y = point print(x, y) # 10.5 20.3 # Single-element tuple needs a trailing comma single = (5,) not_a_tuple = (5) # just an int in parentheses!
💡 The (5,) vs (5) trap is a favorite quick-fire question — mention it unprompted if tuples come up, since it shows real hands-on experience.
What is the difference between a list and a tuple?
Answer
Lists are mutable and intended for homogeneous, variable-length data; tuples are immutable and intended for fixed-structure, heterogeneous records. That single distinction (mutability) drives every practical difference between them.
Key points
- 1Mutability — List: Mutable; Tuple: Immutable
- 2Syntax — List: [1, 2, 3]; Tuple: (1, 2, 3)
- 3Hashable — List: No; Tuple: Yes (if elements are hashable)
- 4Typical use — List: Homogeneous, growing collections; Tuple: Fixed-size records, dict keys
- 5Performance — List: Slightly slower to create/iterate; Tuple: Slightly faster and more memory-efficient
- 6Methods available — List: Many (append, sort, remove,.); Tuple: Few (count, index) — no mutation methods
Example
scores = [90, 85, 70] # will likely grow/shrink/change -> list scores.append(100) rgb = (255, 0, 128) # fixed 3-value structure -> tuple # rgb[0] = 0 # TypeError: 'tuple' object does not support item assignment
💡 A strong answer connects mutability to why you'd choose one, not just what's different syntactically — e.g., "I'd use a tuple to return multiple values from a function because the caller shouldn't be able to accidentally mutate a fixed result."
Why are tuples hashable but lists are not?
Answer
Hashability requires that an object's hash value never changes during its lifetime. Since lists are mutable, their contents (and thus what their hash would be) can change after creation, which would break dictionaries and sets that rely on a stable hash. Tuples, being immutable, can safely compute and cache a hash.
This connects directly to how dictionaries and sets work internally (see Q41 and Q43): both rely on an object's __hash__() staying constant so the object always lands in the same hash bucket. If you could mutate a list after using it as a dict key, its hash would potentially change, and the dictionary would no longer be able to find it — silently corrupting lookups. Python sidesteps this entirely by making list.
__hash__ None, so trying to hash one raises TypeError immediately rather than allowing subtle corruption later.
Example
t = (1, 2, 3) print(hash(t)) # works -- tuples are hashable l = [1, 2, 3] # print(hash(l)) # TypeError: unhashable type: 'list' # Trap: a tuple containing a list is still unhashable mixed = (1, [2, 3]) # print(hash(mixed)) # TypeError -- one unhashable element poisons the whole tuple
What are Python sets, and what are their key properties?
Answer
A set is an unordered collection of unique, hashable elements, implemented as a hash table. Its defining properties are: no duplicates, no guaranteed ordering, and very fast (average O(1)) membership testing.
Sets automatically deduplicate anything you add to them, which makes them the natural tool for "give me only the unique values" and "is X in this collection" problems — membership testing in a set is dramatically faster on average than in a list, because a set doesn't need to scan every element (a list's in check is O(n); a set's is O(1) average).
Example
tags = {"python", "java", "python", "go"} print(tags) # {'python', 'java', 'go'} -- duplicate removed print("java" in tags) # True, O(1) average print(len(tags)) # 3 numbers = set([1, 2, 2, 3, 3, 3]) print(numbers) # {1, 2, 3}
💡 If asked "how would you deduplicate a list fast," list(set(my_list)) is the expected oneliner — but mention that it doesn't preserve order (see Q53 for the order-preserving version).
What are the common set operations in Python?
Answer
Sets support mathematical set operations directly: union (|), intersection (&), difference (-), and symmetric_difference (^).
Each operation has both an operator form and a named-method form (e.g., a | b and a.union(b)); the method form additionally accepts any iterable, not just another set, which is often more convenient.
Example
a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a | b) # union -> {1, 2, 3, 4, 5, 6} print(a & b) # intersection -> {3, 4} print(a - b) # difference -> {1, 2} print(a ^ b) # symmetric difference -> {1, 2, 5, 6} print(a.issubset({1, 2, 3, 4, 5})) # True print(a.isdisjoint({7, 8})) # True -- no overlap
💡 These operators are a natural fit for "find common elements between two lists" or "find items only in list A" questions — converting to sets first is usually the expected optimization over nested loops.
When would you use a set instead of a list?
Answer
Use a set when you need uniqueness, fast membership testing, or mathematical set operations, and don't care about order or duplicates. Use a list when order matters, duplicates are meaningful, or you need to index by position.
Key points
- 1Order — List: Preserved (insertion order); Set: Not guaranteed
- 2Duplicates — List: Allowed; Set: Automatically removed
- 3Membership test (in) — List: O(n); Set: O(1) average
- 4Indexing (x[0]) — List: Yes; Set: No — sets aren't indexable
- 5Element requirement — List: Any object; Set: Must be hashable
Example
visited_urls = set() # fast "have we seen this?" checks for url in crawl_queue: if url not in visited_urls: # O(1) average, vs O(n) for a list visited_urls.add(url) process(url)
💡 A strong answer frames this as "it depends on whether I need order/duplicates/indexing (list) or fast lookups/uniqueness (set)" rather than a blanket preference.
What is a frozenset, and when would you use one?
Answer
A frozenset is an immutable version of a set — same hash-table-backed uniqueness and fast membership testing, but you can't add or remove elements after creation. Because it's immutable, it's also hashable, so it can be used as a dictionary key or nested inside another set.
A regular set cannot be a dictionary key or a member of another set (it's unhashable, like a list), which is exactly the gap frozenset fills. It's less commonly used day-to-day than set, but it comes up whenever you need a "set of sets" or want to use a group of unique values as a lookup key.
Example
fs = frozenset([1, 2, 3]) # fs.add(4) # AttributeError -- frozensets have no mutating methods cache = {} key = frozenset(["python", "java"]) # order-independent, hashable key cache[key] = "matched skill set" print(cache[frozenset(["java", "python"])]) # 'matched skill set' -- order doesn't matter
💡 The "set of sets" or "using an unordered group of values as a cache key" scenario is the cleanest real justification for frozenset — have that example ready rather than a vague "it's just immutable."
What are Python dictionaries, and how are they implemented internally?
Answer
A dict is a mutable mapping of unique, hashable keys to values, implemented internally as a hash table. Since Python 3.7, dictionaries also officially guarantee insertion order is preserved when iterating.
When you insert a key, CPython computes hash(key) and uses it to determine a slot in an internal array. Lookups, insertions, and deletions are all average O(1) because they go almost directly to the right slot rather than scanning every item. Hash collisions (two keys hashing to the same slot) are resolved internally via open addressing. The insertion-order guarantee (3.
7+) is actually a side effect of an internal implementation change (a compact dict layout using a separate insertion-ordered array) that became a language guarantee, not just a CPython quirk.
Example
user = {"name": "Ana", "age": 30} user["email"] = "ana@example.com" # O(1) average insert print(user["name"]) # O(1) average lookup -- 'Ana' print(list(user.keys())) # ['name', 'age', 'email'] -- insertion order preserved
💡 Saying "hash table with O(1) average-case lookup, and insertion order is guaranteed since 3.7" in one sentence covers what most interviewers are fishing for here.
What are the most commonly used dictionary methods?
Answer
The essentials are.get(),.keys(),.values(),.items(),.update(),.pop(), and.setdefault() — covering safe access, iteration, merging, and removal.
.get(key, default) avoids a KeyError by returning a fallback value if the key is missing.setdefault(key, default) is similar but also inserts the default into the dictionary if the key was missing — useful for building up grouped data structures in a single line.
Example
d = {"a": 1, "b": 2} print(d.get("c", 0)) # 0 -- no KeyError d.setdefault("c", []).append(99) print(d) # {'a': 1, 'b': 2, 'c': [99]} d.update({"a": 100, "d": 4}) print(d) # {'a': 100, 'b': 2, 'c': [99], 'd': 4} removed = d.pop("b") print(removed, d) # 2 {'a': 100, 'c': [99], 'd': 4}
💡 .setdefault() combined with collections.defaultdict is a common pattern for grouping data (e.g., "group these words by their first letter") — being fluent with both is worth demonstrating directly.
What makes an object hashable, and why does it matter for dict keys and set members?
Answer
An object is hashable if it implements __hash__() (returning a constant integer for its lifetime) and, generally, __eq__() consistently with that hash. Only hashable objects can be dictionary keys or set members, because both structures rely on hashing to locate items quickly.
The contract is: if a == b, then hash(a) == hash(b) must also hold — otherwise a dictionary could never find a key it previously stored. Built-in immutable types (int, str, tuple of hashables, frozenset) are hashable by default; built-in mutable types (list, dict, set) are not.
Custom class instances are hashable by default (using the object's id()), but defining a custom __eq__() without also defining __hash__() makes instances unhashable.
Example
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __hash__(self): return hash((self.x, self.y)) # must match __eq__'s notion of equality points = {Point(1, 2), Point(1, 2)} print(len(points)) # 1 -- treated as equal and deduplicated
What is the difference between dict.get() and dict[key]?
Answer
dict[key] raises a KeyError if the key doesn't exist. dict.get(key, default) returns None (or a specified default) instead of raising — making it the safer choice when a missing key is a normal, expected case rather than a bug.
Use dict[key] when the key's presence is guaranteed and its absence would indicate a real bug you want surfaced immediately. Use.get() when a missing key is a legitimate, expected possibility that your code should handle gracefully.
Example
config = {"debug": True} print(config["debug"]) # True # print(config["timeout"]) # KeyError: 'timeout' print(config.get("timeout")) # None print(config.get("timeout", 30)) # 30 -- sensible fallback
💡 A good answer explicitly frames this as a design choice ("do I want a missing key to fail loudly or degrade gracefully?"), not just a syntax fact.
What are the different ways to iterate over a dictionary?
Answer
You can iterate over a dictionary's keys directly (the default), or explicitly over.keys(),.values(), or.items() (key-value pairs) depending on what you need.
.items() is the most commonly used in real code since it gives you both the key and value in one pass, avoiding a second lookup with d[key] inside the loop. All three views (.keys(),.values(),.items()) are "live" — they reflect changes made to the dictionary after the view was created, and they don't copy the whole dictionary into memory.
Example
scores = {"Ana": 90, "Ben": 85, "Cy": 78} for name in scores: # iterates keys by default print(name) for name, score in scores.items(): # most common pattern print(f"{name}: {score}") for score in scores.values(): print(score)
💡 Mention that dictionary views are memory-efficient (not full copies) — it's a small detail that separates a surface-level answer from one grounded in how CPython actually works.
What is the difference between a shallow copy and a deep copy?
Answer
A shallow copy creates a new outer object but still references the same nested (inner) objects as the original. A deep copy recursively copies every nested object too, so the copy is fully independent of the original at every level.
This distinction only matters for objects that contain other mutable objects (a list of lists, a dict of lists, etc.). For a "flat" structure of immutable values, shallow and deep copies behave identically. copy.copy() performs a shallow copy; copy.deepcopy() performs a deep copy; slicing (lst[:]) and list(lst) also produce shallow copies.
Example
import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) shallow[0].append(99) print(original) # [[1, 2, 99], [3, 4]] -- original changed! inner list is shared deep = copy.deepcopy(original) deep[0].append(-1) print(original) # [[1, 2, 99], [3, 4]] -- untouched, fully independent copy
How do you safely copy nested or mutable data structures in Python?
Answer
Use copy.deepcopy() from the standard library whenever the structure contains nested mutable objects (lists of lists, dicts of dicts/lists, custom objects holding mutable state) and you need full independence from the original.
For simple, one-level structures of immutable values, a shallow copy (list(x), dict(x), x.copy(), or x[:]) is sufficient and cheaper. deepcopy() handles cycles (an object referencing itself, directly or indirectly) correctly by tracking already-copied objects, so it won't infinite-loop the way a naive recursive copy might.
Example
import copy config = { "servers": ["a.example.com", "b.example.com"], "limits": {"cpu": 4, "memory": 16}, } backup = copy.deepcopy(config) backup["servers"].append("c.example.com") backup["limits"]["cpu"] = 8 print(config["servers"]) # unaffected -- ['a.example.com', 'b.example.com'] print(config["limits"]["cpu"]) # unaffected -- 4
💡 If asked to implement your own deep copy for a custom class, mention __deepcopy__ as the hook copy.deepcopy() looks for — it shows awareness that copying behavior is customizable via the data model.
How do you work with nested data structures in Python?
Answer
Nested structures (a list of dicts, a dict of lists, dicts of dicts) are accessed and modified by chaining indexing/key lookups, and are most safely navigated defensively with.get() at each level to avoid KeyError / IndexError on missing data.
Real-world data (JSON API responses, config files) is almost always nested. The main skills interviewers probe here are: chaining access correctly, modifying a deeply nested value without recreating the whole structure, and handling missing keys gracefully rather than crashing on the first malformed record.
Example
data = { "user": {"name": "Ana", "roles": ["admin", "editor"]}, "active": True, } print(data["user"]["name"]) # 'Ana' print(data["user"]["roles"][0]) # 'admin' data["user"]["roles"].append("viewer") # mutate nested list in place print(data["user"].get("email", "n/a")) # 'n/a' -- safe default for missing key # Safe nested access without a KeyError explosion city = data.get("user", {}).get("address", {}).get("city", "unknown") print(city) # 'unknown'
💡 Chained.get() calls with defaults at every level is the expected "defensive" pattern for parsing real-world JSON where fields might be missing — bring this up unprompted when discussing API response handling.
What are list comprehensions, and why are they preferred over explicit loops?
Answer
A list comprehension builds a new list in a single, declarative expression: [expression for item in iterable if condition]. They're preferred for simple transformations/filters because they're more concise, often faster, and read closer to "what" you want rather than "how" to build it step by step.
Comprehensions are typically faster than the equivalent for loop with.append() because the looping happens in optimized C code internally, rather than through repeated Python-level method calls. That said, once a comprehension needs multiple conditions, nested loops, or side effects, readability drops fast — at that point, a regular loop is the better (and more Pythonic) choice.
Example
# Traditional loop squares = [] for n in range(10): if n % 2 == 0: squares.append(n ** 2) # Equivalent comprehension squares = [n ** 2 for n in range(10) if n % 2 == 0] print(squares) # [0, 4, 16, 36, 64] # Nested comprehension: flatten a matrix matrix = [[1, 2], [3, 4], [5, 6]] flat = [n for row in matrix for n in row] print(flat) # [1, 2, 3, 4, 5, 6]
💡 If a comprehension needs more than one for or more than one if / else, say so explicitly — "I'd break this into a regular loop past this point for readability" is a strong, senior-sounding answer.
What are dictionary and set comprehensions?
Answer
They apply the same comprehension syntax to build dictionaries and sets instead of lists: {k: v for.} for a dict comprehension, {expr for.} for a set comprehension.
The syntax is visually similar to a dict/set literal, distinguished from a list comprehension by curly braces instead of square brackets, and from each other by whether there's a key: value pair or a single expression inside.
Example
names = ["ana", "ben", "cy"] # Dict comprehension: name -> length lengths = {name: len(name) for name in names} print(lengths) # {'ana': 3, 'ben': 3, 'cy': 2} # Set comprehension: unique lengths unique_lengths = {len(name) for name in names} print(unique_lengths) # {2, 3} # Inverting a dictionary original = {"a": 1, "b": 2} inverted = {v: k for k, v in original.items()} print(inverted) # {1: 'a', 2: 'b'}
💡 "Invert a dictionary" is a very common live-coding micro-task — the one-liner {v: k for k, v in d.items()} (with a caveat about duplicate values overwriting each other) is worth having ready instantly.
What is a generator expression, and how does it differ from a list comprehension?
Answer
A generator expression uses the same syntax as a list comprehension but with parentheses instead of brackets — (x for x in iterable) — and produces values lazily, one at a time, instead of building the entire result in memory up front.
A list comprehension computes and stores every item immediately, which is fine for small collections but wasteful (or impossible) for very large or infinite sequences. A generator expression instead returns a generator object that produces the next value only when asked (via next() or a for loop), making it far more memory-efficient for large data. This topic is covered in much more depth in (Iterators & Generators).
Example
# List comprehension: builds the full list of 10 million items in memory now squares_list = [n ** 2 for n in range(10_000_000)] # Generator expression: computes each value on demand, negligible memory footprint squares_gen = (n ** 2 for n in range(10_000_000)) print(next(squares_gen)) # 0 -- computed just now print(next(squares_gen)) # 1 -- computed just now print(sum(n ** 2 for n in range(1000))) # generators work directly with sum(), etc.
💡 If a question mentions processing a huge file or dataset, reaching for a generator expression instead of a list comprehension is exactly the kind of memory-awareness interviewers are listening for.
What is the difference between sort() and sorted()?
Answer
list.sort() sorts a list in place and returns None. The built-in sorted() returns a new sorted list (or sequence, from any iterable) and leaves the original untouched.
Both accept key= (a function to customize sort criteria) and reverse=True. sorted() works on any iterable (lists, tuples, dict keys, generators), while.sort() is a method that only exists on lists. A very common bug is writing my_list = my_list.sort(), which sets my_list to None because.sort() doesn't return the sorted list.
Example
nums = [3, 1, 4, 1, 5] new_sorted = sorted(nums) # new list, original untouched print(new_sorted, nums) # [1, 1, 3, 4, 5] [3, 1, 4, 1, 5] nums.sort() # mutates nums in place print(nums) # [1, 1, 3, 4, 5] words = ["banana", "kiwi", "apple"] print(sorted(words, key=len)) # ['kiwi', 'apple', 'banana'] -- sort by length print(sorted(words, reverse=True)) # ['kiwi', 'banana', 'apple'] -- descending
How would you remove duplicates from a list while preserving order?
Answer
list(set(my_list)) removes duplicates but loses order. To preserve order, iterate manually while tracking what's already been seen — or, more idiomatically in modern Python, use dict.fromkeys(my_list), which relies on dicts preserving insertion order since 3.7.
dict.fromkeys() builds a dictionary using each list item as a key (deduplicating automatically) with no values needed, then you convert its keys back into a list. This is the idiomatic one-liner for this exact interview question in modern Python.
Example
items = [3, 1, 4, 1, 5, 3, 9, 1] # Loses order: no_order = list(set(items)) print(no_order) # e.g. [1, 3, 4, 5, 9] -- order not guaranteed # Preserves order (idiomatic, Python 3.7+): ordered = list(dict.fromkeys(items)) print(ordered) # [3, 1, 4, 5, 9] # Manual approach (also valid, more explicit): seen = set() ordered_manual = [] for x in items: if x not in seen: seen.add(x) ordered_manual.append(x) print(ordered_manual) # [3, 1, 4, 5, 9]
💡 Offer dict.fromkeys() as the concise idiomatic answer, but also walk through the manual seen = set() version — interviewers often want to see that you understand why it works (O(1) average membership checks), not just that you know the trick.
What are the different ways to merge two dictionaries in Python?
Answer
Common approaches are.update() (mutates in place), the {**a, **b} unpacking syntax (creates a new dict, Python 3.5+), and the | merge operator (creates a new dict, Python 3.9+). In every case, keys from the second/ right-hand dictionary win on conflicts.
Choosing between them is mostly about whether you want to mutate an existing dictionary or produce a new one, and which Python version you're targeting.
Example
a = {"x": 1, "y": 2} b = {"y": 20, "z": 3} merged_new = {**a, **b} # new dict; b's values win on conflict print(merged_new) # {'x': 1, 'y': 20, 'z': 3} merged_operator = a | b # Python 3.9+, also a new dict print(merged_operator) # {'x': 1, 'y': 20, 'z': 3} a.update(b) # mutates 'a' in place print(a) # {'x': 1, 'y': 20, 'z': 3}
💡 Mentioning that the | operator was only added in 3.9, and offering {**a, **b} as the more broadly compatible alternative, shows version-awareness that a lot of candidates miss.
How does Python compare collections like lists, dicts, and sets for equality?
Answer
== on collections compares by value, recursively — two lists are equal if they have the same items in the same order; two dicts are equal if they have the same key-value pairs regardless of insertion order; two sets are equal if they contain the same elements regardless of order.
This is a direct extension of Q9 (is vs ==) applied to collections: == never cares about identity or memory location, only content. Order matters for lists and tuples (since they're sequences) but not for dicts or sets (since they're unordered by nature, even though modern dicts happen to preserve insertion order for iteration purposes).
Example
print([1, 2, 3] == [1, 2, 3]) # True -- same order, same values print([1, 2, 3] == [3, 2, 1]) # False -- order matters for lists print({"a": 1, "b": 2} == {"b": 2, "a": 1}) # True -- dict equality ignores key order print({1, 2, 3} == {3, 2, 1}) # True -- set equality ignores order entirely a, b = [1, 2, 3], [1, 2, 3] print(a == b, a is b) # True False -- equal value, different objects
💡 This question is a good opportunity to tie several earlier concepts together in one answer: value vs identity (== vs is), and how each collection type's notion of "order" (or lack of it) affects equality.
Recommended resourcesAffiliate links · may earn us a commission