Unexpected result of checking type of values in a list - with regards to Booleans

Viewed 15

When I have a list containing different values, I tried to check the type of each value and got an unexpected output. It was the Booleans True and False which threw me off. Follows the code and the results.

trial_set = {1,2,3,4,None, True, False}

new_list = [type(x) for x in trial_set]
new_set = {type(x) for x in trial_set}

print(new_list)
print(new_set)

Strange Boolean Type Behaviour

Questions:

  1. Why does the datatype appear first in the output though they are the last two elements in the list?
  2. Why is there only one datatype in output when I have two Booleans in the list?

I understand that Bool datatype is a substring of integer datatype and return 0 or 1 and I tried to figure this out from that angle but came up empty. Please help clarify.

Thank you in advance.

1 Answers

The result is because of the way Python sets work as well as how Booleans work under the hood. Since True == 1 in python, only a single occurrence of 1 or True will appear, in this case 1.

Also, sets in python are unordered so when you iterate it with a comprehension to make a list, the order is not guaranteed to be as you typed it.

Related