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.
The difference isn't what they hold — it's what they guarantee:
[…] is an ordered, mutable sequence that keeps duplicates — Java's
ArrayList. Use it as your default "bunch of things in order I'll change."(…) is an ordered sequence that is immutable — fixed once built.
Use it for a small fixed record (an (x, y) point, a row) or any time you want a value that
can't be accidentally mutated. Because it can't change, a tuple is hashable, so it can be a
dict key or a set member; a list cannot.{…} is an unordered collection of unique items — Java's
HashSet. It silently drops duplicates and answers "is x in here?" in roughly
constant time instead of scanning the whole thing.Type a few items (commas separate them — repeat one to see what de-duplicates):
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:
A | B — union: everything in either.A & B — intersection: only what's in both.A - B — difference: in A but not B.A ^ B — symmetric difference: in exactly one, not both.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:
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.
| & - ^). Mutability and hashability are two sides of the
same coin — see names & objects.Step through how these are stored in memory with Python Tutor.