Difference Between List and Set

Python List and Set

Probuse Admin


- You can use a list if you have an ordered collection of items. That means you want to your items in partiacular order. List keep your ordering.


- You can use a set to store an unordered set of items. That means you do not care about ordering of items then you should go with set. Using set it forbids duplicates. set requires items to be hashable.


An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().

Note: tuple is hashable because it is immutable whereas a list is mutable. The keys of a dict have to be immutable. Lists are mutable, tuples are not. All of Python’s immutable built-in objects are hashable.

hashable = immutable = set

non-hashable = mutable = list