sets anomaly
Ned Batchelder
ned at nedbatchelder.com
Wed Dec 7 10:33:59 EST 2016
On Wednesday, December 7, 2016 at 10:18:32 AM UTC-5, Rustom Mody wrote:
> Trying to write some code using sets (well frozen sets)
> And was hit by this anomaly
>
> This is the behavior of lists I analogously expect in sets:
>
> >>> []
> []
> >>> [[]]
> [[]]
> >>>
>
> ie the empty list and the list of the empty list are different things
>
> However
> (with
> f= frozenset
> )
>
> >>> f()
> frozenset()
> >>> f([])
> frozenset()
> >>> f(f([]))
> frozenset()
> >>>
The difference is more about the difference between the behavior of a
callable constructor, and a list literal. Lists will behave the same
as frozenset if you use list():
>>> list()
[]
>>> list(list())
[]
>>> list(list(list()))
[]
This is because the constructors can take a sequence, and use those
elements as the new contents. List literals don't work that way.
> Spent a good ½ hour finding out this strangeness
> And then some figuring out how to get an empty set into a set
> This is the best I get:
> >>> f([f([])])
> frozenset({frozenset()})
That is the way I would have done it also. Or:
>>> s = set()
>>> s.add(frozenset())
>>> frozenset(s)
frozenset([frozenset([])])
Notice the repr output of the result shows how to make it! :)
--Ned.
More information about the Python-list
mailing list