list · tuple · set

Three built-in containers that look interchangeable but encode three different promises. Picking the right one is half of writing Pythonic code — and it maps cleanly onto containers you already know from Java: ArrayList, an immutable record, and HashSet.

mutable vs immutableordered de-duplicationset algebra hashable

Same items, three contracts

The difference isn't what they hold — it's what they guarantee:

Type a few items (commas separate them — repeat one to see what de-duplicates):

Sets are algebra, not just storage

The real power of a set is that it brings the operations of mathematical set theory into your code as fast one-liners. Membership testing (x in s), and combining two sets:

These show up constantly: "which users are in group A but not B?", "which features do two models share?" Pick an operation and watch which region lights up.

Expression:

Result:

How to choose — a 3-question test

  1. Will it change? No → tuple. Yes → list or set.
  2. Do duplicates matter / does order matter? Yes → list. No → set.
  3. Will I test membership a lot, on big data? Strongly favour a set — x in big_set is ~O(1), x in big_list is O(n).

One caveat: a set's speed comes from hashing, so its members must be hashable (immutable). You can put numbers, strings, and tuples in a set, but not lists or dicts. That's the same reason a tuple can be a dict key and a list can't — see the dict explainer.

Takeaways: list = ordered, mutable, keeps dups (your default). tuple = ordered, immutable, hashable (fixed records / dict keys). set = unordered, unique, fast membership + set algebra (| & - ^). Mutability and hashability are two sides of the same coin — see names & objects.

Step through how these are stored in memory with Python Tutor.