Python data structures interview questions
25 questions interviewers ask on data structures, from first principles to the follow-ups. The first 3 model answers are free to read; Pro opens the rest.
Choosing a structure
- What is the difference between a list, a tuple, a set and a dictionary?●
A list is an ordered, mutable sequence, read by index. A tuple is an ordered sequence that can not be changed. A set holds each value at most once, has no order and no index, and answers
inquickly. A dictionary maps keys to values, keeps insertion order, and is read by key. - When would you choose a tuple over a list?●●
When the number of values is fixed and each position has its own meaning: a coordinate
(lat, lon), a date(year, month, day), a database row. A tuple of hashable values is also hashable, so it can be a set member or a dictionary key, which a list can not:{[12.9716, 77.5946]}givesTypeError: unhashable type: 'list'. - Why is
x in some_setfaster thanx in some_list?●●inon a list compares the value with each element in turn until one matches, so its time grows with the list. A set computes the value's hash and selects candidate positions, checking equality as needed; collisions can require extra probes. Lookup time is roughly constant on average, not guaranteed. On the recording machine,999_999 ina list of a million integers took about 6 ms, and the same check on a set about 24 ns. Building the set costs a full pass, so a set pays off when there are many checks. - What does "hashable" mean, and which built-in types are hashable?●●
Lists
- What do
week[-1],week[-3:]andweek[::-1]give?● - What happens when you index past the end of a list, and when you slice past it?●
- What is the difference between
sort()andsorted()?●● - What is aliasing? How do you copy a list?●●
- What is the difference between
x = x + [4]andx += [4]for a list?●● - What does
[[0] * 3] * 3build, and why is it a trap?●● - Why should you not remove items from a list while looping over it?●●
Tuples
- How do you write a tuple with one item?●
- Can a tuple change?●●
- What is unpacking, and what happens when the counts do not match?●●
Sets
- How do you create an empty set?●
- What are union, intersection, difference and symmetric difference?●●
- What is the difference between a set's
removeanddiscard?●●
Dictionaries
- What is the difference between
d[key]andd.get(key)?● - Are dictionaries ordered?●●
- How do you count items in Python?●●
- What is a
defaultdict, and what is its trap?●● - How do you loop over a dictionary's keys and values together?●●
Strings
- Strings are immutable. What does that mean for their methods?●●
- How do you check whether a string is a palindrome?●●
Comprehensions
- What is a list comprehension, and when should you not use one?●●