0
myset = {3, 4, 5, 1, 23, 45, 23, 89, "rohit", "raman", "rohit", 4, 5 , True, False,  3j}
print(myset)

# Output-
{False, 1, 3, 4, 5, 3j, 'raman', 45, 23, 89, 'rohit'}

My question is why its not printing "True" in output, but its printing "False". If it can print False then why not True?

InSync
  • 4,851
  • 4
  • 8
  • 30
Dip Kri
  • 1
  • 1

2 Answers2

0

For set and dict types in Python, the rule for seeing if a value already exists is if any value in the existing set or dict compares equal to the new value, i.e. if old_val == new_val is True. (It is assumed that such values will also have the same hash value.)

In this case, 1 and True compare as equal, i.e. 1 == True is True. When this happens, the old element is retained, including its type. Since 1 appeared before True, the set ends up containing 1 rather than True. If you reverse the order of the two elements, you'll end up with a set that contains True but not 1.

You can see a similar effect with 0 and False. Note that 0.0, 0j, etc. also compare equal to 0.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

Have a short look at the docs: A set object is an unordered collection of distinct hashable objects.

A set has to have unique members. And a set does not maintain an order.

Because of this, the doubled items 4, 5, "rohit" are kicked out. As True==1 the True is also kicked. The rest of your items are rearranged, and as False==0 it happens to be in first place, but with no guarantee that this will always be the case. If you add another element 0 with your set, preferably before False, the False will also be replaced.

Remember, in Python your boolean variables are kind of integers.

destructioneer
  • 150
  • 1
  • 10