Is python's "set" stable? -
the question arose when answering question (there).
when iterate several times on python set (without changing between calls), can assume return elements in same order? , if not, rationale of changing order ? deterministic, or random? or implementation defined?
and when call same python program repeatedly (not random, not input dependent), same ordering sets?
the underlying question if python set iteration order depends on algorithm used implement sets, or on execution context?
there's no formal guarantee stability of sets (or dicts, matter.) however, in cpython implementation, long nothing changes set, items produced in same order. sets implemented open-addressing hashtables (with prime probe), inserting or removing items can change order (in particular, when triggers resize, reorganizes how items laid out in memory.) can have 2 identical sets nonetheless produce items in different order, example:
>>> s1 = {-1, -2} >>> s2 = {-2, -1} >>> s1 == s2 true >>> list(s1), list(s2) ([-1, -2], [-2, -1])
unless you're have same set , nothing touched inbetween 2 iterations, it's best not rely on staying same. making seemingly irrelevant changes to, say, functions call inbetween produce hard find bugs.
Comments
Post a Comment