Skip to content Skip to sidebar Skip to footer

Adding The Number 1 To A Set Has No Effect

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, 'Vanill

Solution 1:

>>> 1 == TrueTrue

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

>>> st
{'a', True, 'Vanilla'}
>>> 1in 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.

Solution 2:

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.

Solution 3:

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.

Solution 4:

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

Solution 5:

We have to use a list if you want to have items with the same hash.If you're absolutely sure your set needs to be able to contain both True and 1.0, I'm pretty sure you'll have to define your own custom class, probably as a thin wrapper around dict. As in many languages, Python's set type is just a thin wrapper around dict where we're only interested in the keys.

Ex:

st = {'a', True, 'Vanilla'}

list_st = []

for i in st:
    list_st.append(i)
    
list_st.append(1)

for i in list_st:
    print(f'The hash of {i} is {hash(i)}')

produces

The hash of Trueis1
The hash of Vanilla is -6149594130004184476
The hash of a is8287428602346617974
The hash of 1is1

[Program finished]

Post a Comment for "Adding The Number 1 To A Set Has No Effect"