pkaramol
pkaramol

Reputation: 19402

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?

Upvotes: 12

Views: 1699

Answers (2)

Mohamed Slama
Mohamed Slama

Reputation: 197

Here is an example of how the mechanism of sets to get distinct values works:

def get_distinct_values(values):
  set_of_values = set()
  for value in values:
    hash_value = hash(value)
    set_of_values.update([value])
  return set_of_values

get_distinct_values([1,2,True,False,int(0.5)])

Output:

{False, 1, 2}

Upvotes: 0

krethika
krethika

Reputation: 4496

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.

Upvotes: 13

Related Questions