Why are tuples constructed from differently initialized sets equal?

前端 未结 4 1124
无人共我
无人共我 2021-02-05 00:48

I expected the following two tuples

>>> x = tuple(set([1, \"a\", \"b\", \"c\", \"z\", \"f\"]))
>>> y = tuple(set([\"a\", \"b\", \"c\", \"z\", \         


        
4条回答
  •  青春惊慌失措
    2021-02-05 01:33

    There are two things at play here.

    1. Sets are unordered. set([1, "a", "b", "c", "z", "f"])) == set(["a", "b", "c", "z", "f", 1])

    2. When you convert a set to a tuple via the tuple constructor it essentially iterates over the set and adds each element returned by the iteration .

    The constructor syntax for tuples is

    tuple(iterable) -> tuple initialized from iterable's items
    

    Calling tuple(set([1, "a", "b", "c", "z", "f"])) is the same as calling tuple([i for i in set([1, "a", "b", "c", "z", "f"])])

    The values for

    [i for i in set([1, "a", "b", "c", "z", "f"])]
    

    and

    [i for i in set(["a", "b", "c", "z", "f", 1])]
    

    are the same as it iterates over the same set.

    EDIT thanks to @ZeroPiraeus (check his answer ). This is not guaranteed. The value of the iteration will not always be the same even for the same set.

    The tuple constructor doesn't know the order in which the set is constructed.

提交回复
热议问题