SchoolWhool
Quizzes and saved progress, freeSign in freeSign in
Python · Module 3Module material

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

  1. 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 in quickly. A dictionary maps keys to values, keeps insertion order, and is read by key.

  2. 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]} gives TypeError: unhashable type: 'list'.

  3. Why is x in some_set faster than x in some_list?●●

    in on 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 in a 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.

  4. What does "hashable" mean, and which built-in types are hashable?●●

Lists

  1. What do week[-1], week[-3:] and week[::-1] give?●
  2. What happens when you index past the end of a list, and when you slice past it?●
  3. What is the difference between sort() and sorted()?●●
  4. What is aliasing? How do you copy a list?●●
  5. What is the difference between x = x + [4] and x += [4] for a list?●●
  6. What does [[0] * 3] * 3 build, and why is it a trap?●●
  7. Why should you not remove items from a list while looping over it?●●

Tuples

  1. How do you write a tuple with one item?●
  2. Can a tuple change?●●
  3. What is unpacking, and what happens when the counts do not match?●●

Sets

  1. How do you create an empty set?●
  2. What are union, intersection, difference and symmetric difference?●●
  3. What is the difference between a set's remove and discard?●●

Dictionaries

  1. What is the difference between d[key] and d.get(key)?●
  2. Are dictionaries ordered?●●
  3. How do you count items in Python?●●
  4. What is a defaultdict, and what is its trap?●●
  5. How do you loop over a dictionary's keys and values together?●●

Strings

  1. Strings are immutable. What does that mean for their methods?●●
  2. How do you check whether a string is a palindrome?●●

Comprehensions

  1. What is a list comprehension, and when should you not use one?●●