Adding the number 1 to a set has no effect

2019-02-16 18:37发布

I cannot add the integer number 1 to an existing set. In an interactive shell, this is what I am doing:

>>> st = {'a', True, 'Vanilla'}
>>> st
{'a', True, 'Vanilla'}
>>> st.add(1)
>>> st
{'a', True, 'Vanilla'}   # Here's the problem; there's no 1, but anything else works
>>> st.add(2)
>>> st
{'a', True, 'Vanilla', 2}

This question was posted two months ago, but I believe it was misunderstood. I am using Python 3.2.3.

4条回答
SAY GOODBYE
2楼-- · 2019-02-16 18:52

I believe, though I'm not certain, that because hash(1) == hash(True) and also 1 == True that they are considered the same elements by the set. I don't believe that should be the case, as 1 is True is False, but I believe it explains why you can't add it.

查看更多
贪生不怕死
3楼-- · 2019-02-16 18:57

1 is equivalent to True as 1 == True returns true. As a result the insertion of 1 is rejected as a set cannot have duplicates.

查看更多
forever°为你锁心
4楼-- · 2019-02-16 19:01
>>> 1 == True
True

I believe your problem is that 1 and True are the same value, so 1 is "already in the set".

>>> st
{'a', True, 'Vanilla'}
>>> 1 in st
True

In mathematical operations True is itself treated as 1:

>>> 5 + True
6
>>> True * 2
2
>>> 3. / (True + True)
1.5

Though True is a bool and 1 is an int:

>>> type(True)
<class 'bool'>
>>> type(1)
<class 'int'>

Because 1 in st returns True, I think you shouldn't have any problems with it. It is a very strange result though. If you're interested in further reading, @Lattyware points to PEP 285 which explains this issue in depth.

查看更多
对你真心纯属浪费
5楼-- · 2019-02-16 19:12

Here are some link if anyone is interested in further study.

Is it Pythonic to use bools as ints?

https://stackoverflow.com/a/2764099/1355722

查看更多
登录 后发表回答