[Python] Is iteration order of a set in Python preserved until that set is modified?

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    According to https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset, set is a mutable unordered collection.

    Usually, it's implemented as a hash table that stores references to objects as its keys.
    Comparing to dict (which is also usually a hash table), dictionary's order of elements is guaranteed to be insertion order since Python 3.7. For set, it is not.

    There is beautiful in-depth explanation about Python dicts and sets implementation behaviour: Why is the order in dictionaries and sets arbitrary?

    But it remains unclear: can it be that a set will be internally rehashed or reallocated by Python interpreter during the execution of some code that doesn't modify that set explicitly? Or is it guaranteed to be stable within this run of a program? Does it depend on set size?

    s = {1, 4, 3, 5}
    iter_result = [i for i in s]

    # some other code not modifying set

    assert [i for i in s] == iter_result # always true within this run???

    Continue reading...

Compartilhe esta Página