max and min values for a list with boolean and integer values

81 Views Asked by At
a=[0, True, False, 1]
a.sort() 
max(a)
min(a)

After sorting, the value of a becomes [0, False, True, 1]. On what basis, python sorts the original list like this when it is said that True is equal to 1 nd False is equal to 0.

  • max(a) gives True as the result
  • min(a) gives 0 as the result

How does Python treat boolean True as bigger than 1? How does Python treat 0 as less than False?

Unable to comprehend how python compares boolean values with integers.

2

There are 2 best solutions below

0
Weijun Zhou On

How does Python treat boolean True as bigger than 1? How does Python treat 0 as lesser than False?

Python does not treat True as larger than 1. It just returns the first one if there are multiple maximal elements. Quote from the official documentation:

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools ...

The same goes for min(). max() returns True because it is equal to 1 and comes earlier in your input, not because somehow True is larger than 1. This is evidenced by that if you switch 1 and True in a, you get 1 as max(a).


On what basis, python sorts the original list like this...

list.sort() in python is stable. 0 and False compare equal, but 0 comes before False in the original a, so after a.sort(), 0 is ordered before False. Same reasoning for why True comes before 1.

0
supsayan On

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal

python documentation.

You get your result just because your list has equal values in this specific order.