There are a lot of container types available in the Python standard library, and it can be confusing sometimes to keep track of them all.
James Bennett goes through and discusses each one. James’ advice:
- Use a
list
for most cases where you just want an iterable/indexable sequence.- Use a
tuple
as a struct-like type where multiple instances will have the same structure, but consider using named tuples to make that structure clearer (a lot of people don’t like named tuples because of the fact that they support iteration and numeric indexing as well as named field access, but I don’t personally mind this).- Use
dict
for key-value mappings.- Use
set
when uniqueness matters, though this is not super common; most of the value of sets is in the union/intersection/etc. operations they support.- Don’t use
dataclass
as a “super-tuple”; if what you really want is just a plain data container with named field access, just use a named tuple. Usedataclass
when you also want the result to be an ordinary mutable Python class (tuples are immutable) with potentially extra behavior attached via methods.- Avoid most of the other container types unless you know they’re the right thing for your specific use case. And if you’re not sure whether they’re right, they aren’t; you generally will just know when one of them is the right fit (for example,
collections.Counter
is very useful for the exact specific thing it does, and not really useful at all for anything else).
See the whole discussion in the post here.