sets anomaly

MRAB python at mrabarnett.plus.com
Wed Dec 7 13:26:17 EST 2016


On 2016-12-07 15:33, Ned Batchelder wrote:
> 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! :)
>
You must be using Python 2 because on Python 3 I get:

 >>> frozenset([frozenset()])
frozenset({frozenset()})



More information about the Python-list mailing list