Back

Question:

Why isn't set a sequence even though it can store multiple values?

How often asked: Rarely

Suggested by: ALittleMoron


Answer:

set is a collection because it can store multiple elements within itself, but that is not enough for it to be considered a sequence.

A sequence gives every element a defined position: first, second, third, and so on. Therefore, sequences support indexing and usually slicing:

items = ["a", "b", "c"]

items[0]    # "a"
items[1:]   # ["b", "c"]

Elements in a set do not have defined positions:

items = {"a", "b", "c"}

items[0]  # TypeError

A set is designed for different purposes:

  • storing unique elements;
  • fast membership testing with in;
  • set operations such as union, intersection, and difference.

Interview answer explanation:

The interviewer is checking whether the candidate:

  • understands the difference between a collection and a sequence;
  • knows the fundamental properties of a set;
  • understands that storing multiple elements does not automatically make a structure a sequence;
  • can select a data structure based on the required operations;
  • understands the role of hashing in set implementation.

A strong candidate should go beyond saying that “sets are unordered” and explain the absence of positional semantics, indexing, and slicing.


External resources:

  • Python official docs

    It's best to start learning anything about a language with its official documentation. It may be confusing, but it's the primary source, meaning you're less likely to get misinformation on the topic you're interested in. The official Python documentation is also well-written and explains data types well.