Predict the output · Python
Collections
Lists, sets and maps: order, duplicates, removal and missing keys.
Learn: Predicting what Python lists, dicts and sets print7 minute read
Python's built-in collections are the list, the tuple (an ordered group of values that cannot change), the dict (a map from keys to values) and the set (a group of unique values). They are simple to use, so interviewers ask about their edge cases instead: test data, expected results and parsed JSON (data read from a common text format) all live in them. These rules decide what list, tuple, dict and set code prints.
Lists: which methods return something
Methods that change a list in place (the same list is changed, and no new list is made), such as append, extend, sort, reverse and remove, return None. So a = a.sort() loses the list. sorted(a) returns a new sorted list and leaves a alone. pop() removes and returns the last item, and pop(i) the item at position i. remove(x) deletes the first item equal to x, and del a[i] deletes by position.
append adds its argument (the value you pass in the brackets) as one item, even if it is a list. extend adds each item of its argument; a string is a sequence of characters, so extending with "hi" adds two items.
a = [3, 1, 2] print(a.sort(), a) a.append([4]) a.extend([5]) print(a, len(a)) print(a.pop(), a.pop(0), a)
None [1, 2, 3] [1, 2, 3, [4], 5] 5 5 1 [2, 3, [4]]
Removing while looping skips items
A for loop over a list walks it by position. Removing an item shifts the following items one place left, so the item that moves into the current position is skipped. Python raises no error. Loop over a copy, or build a new list with a comprehension (a short loop that builds a list) such as [n for n in nums if n != 2].
Tuples: the comma makes the tuple
A tuple is an ordered collection that cannot be changed. (7) is just the number 7 in brackets. (7,) is a one-item tuple, and 1, 2 is a tuple without any brackets. A tuple cannot change, but a list stored inside a tuple can.
Dicts: insertion order and one value per key
Dicts keep keys in the order they were first inserted. Assigning to an existing key replaces the value and keeps the key in its place, and a dict literal (a dict written out with curly brackets) with a repeated key keeps the last value. d[key] raises KeyError (an error that stops the program) for a missing key, while d.get(key) returns None or the default you pass. Keys match by equality and by hash (a number computed from the value, used to find it quickly), so 1, 1.0 and True are the same key. Counting with counts[w] = counts.get(w, 0) + 1 is a common pattern.
Sets: no duplicates and no order to rely on
A set keeps one copy of each value, so its length counts distinct values, and in checks are fast. Do not predict the printed order of a set: for strings it can even change from one run to the next, because the hash numbers of strings are different each time you start Python. Interview snippets that print a set should sort it first, as the sample below does.
d = {"k": 1, "k": 2}
print(d, d.get("z"), d.get("z", 0))
print(sorted({3, 1, 3}))
print(type((7)).__name__, type((7,)).__name__)
{'k': 2} None 0
[1, 3]
int tuple
Slices create new lists; slice assignment edits in place
A slice is a part of a list, written a[start:stop] (see Strings for how slices work). a[1:3] returns a new list. Assigning to a slice, as in a[1:3] = [9], replaces that part of the same list and can change its length. a[::2] takes every second item, and a[-1] is the last one.
How collections print
A list, tuple or dict prints its items with repr(), so strings inside show quotes: ['a', 'b']. An empty set prints as set(), because {} is an empty dict.
How to answer in an interview
Say what each call returns as well as what it changes. "sort() sorts in place and returns None, so the first value printed is None." For a dict, name the rule: one value per key, insertion order kept. When a snippet removes items inside a loop, explain the skipped item and give the fix in the same answer.
Common mistakes
- Writing
a = a.sort(). - Using
appendwhen you meantextend. - Removing items from a list while looping over it.
- Writing
(5)when a one-item tuple was meant. - Reading a missing key with
[]whengetwas safer. - Predicting the printed order of a set.
Recap
In-place list methods return None. Removing while looping skips items. The comma makes a tuple. Dicts keep insertion order and one value per key, and get never raises. Sets drop duplicates and have no reliable order.
11 questions0/11 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | The same key twice in a dict | Easy | |
| Not started | A set built from a list with repeats | Easy | |
| Pro+ | d.get(key) versus d[key] for a missing key | Easy-Medium | |
| Pro+ | Counting with dict.get | Easy-Medium | Asked in: Accenture |
| Pro+ | append versus extend | Easy-Medium | Asked in: TCS |
| Pro+ | list.sort() versus sorted() | Easy-Medium | |
| Pro+ | remove, pop and del on a list | Medium | |
| Pro+ | (5) versus (5,) | Medium | |
| Pro+ | Assigning to a slice | Medium | |
| Pro+ | Removing items from a list while looping over it | Medium-Hard | |
| Pro+ | 1, True and 1.0 as dict keys | Hard | Asked in: Infosys |
The first 2 questions of each topic are free. Pro+ opens every question.