Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

Python set interpetation of 1 and True

In IPython 3 interactive shell:

In [53]: set2 = {1, 2, True, "hello"}

In [54]: len(set2)
Out[54]: 3

In [55]: set2
Out[55]: {'hello', True, 2}

Is that because 1 and True get the same interpetation so given that set eliminates duplicates, only one of them (True) gets to stay? How can we keep both?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A set is a collection of hashables. Even though the statement 1 is True is False, the statement 1 == True is True. Because of that, they have the same hash value and cannot exist separately in a set, and you cannot keep them both in a set

EDIT To make it explicit, as jme pointed out, it is because BOTH things are true - they are equal (per __eq__) AND they have the same hash value (per __hash__).

In a perfect world, equal objects would also have the same hash value, and thankfully this is true for built-in types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...