DEV Community

Pp
Pp

Posted on

Ordered vs Unordered Types in Python

Ordered types

list: keeps elements in the order you insert them. so index positions = order.
tuple: same as list but immutable. It preserves the order of elements because positions are fixed once created.
dict: since Python 3.7, dictionaries preserve insertion order. Internally it’s still a hash table, but it keeps a linked index array that remembers the order keys.

[ 10 ] → [ 20 ] → [ 30 ]
  0        1        2
Enter fullscreen mode Exit fullscreen mode

Unordered types

set: implemented as a hash table with no extra mechanism to track insertion order. Elements go into “buckets” based on their hash
frozenset: same as set but immutable. Still based on hash table, so no order guarantee.

Bucket 0: 30
Bucket 1: 10
Bucket 2: 20
Enter fullscreen mode Exit fullscreen mode

Add another element? Python might reorganize all buckets:

Bucket 0: 20
Bucket 1: 30
Bucket 2: 10
Bucket 3: 40
Enter fullscreen mode Exit fullscreen mode

Run this multiple times:
list, tuple, dict → always in the same order.
set, frozenset → order may appear stable for small runs, but not guaranteed.

ordered_unordered_types_examples

Keeping things ordered always requires extra mechanism on top of the raw storage.

Unordered (set) = just buckets (fast + light).
Ordered (dict/list/tuple) = buckets + extra tracking of positions (more memory, but predictable).

Top comments (0)