Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come I can add the boolean value False but not True in a set in Python? [duplicate]

Tags:

python

set

I just started investigating the set data type in Python. For some reason, whenever I add the Boolean value of True to a set it doesn't appear. However, if I add False to a set it will become an element of the set. I was shocked when I googled this question that nothing came up.

example1 = {1, 2, 7, False} example2 = {7, 2, 4, 1, True}  print(example1) print(example2) 

The output is:

{False, 1, 2, 7} {1, 2, 4, 7} 
like image 509
DJ Poland Avatar asked Jul 24 '18 19:07

DJ Poland


People also ask

Does a boolean have to be true or false?

A Boolean variable has only two possible values: true or false. It is common to use Booleans with control statements to determine the flow of a program.

How do you set true to false in Python?

The bool() in-built Function It takes one parameter on which you want to apply the procedure. However, passing a parameter to the bool() method is optional, and if not passed one, it simply returns False. It returns True if the value of x is True or it evaluates to True, else it returns False.

Can you add true and false in Python?

You can't assign to False because it's a keyword in Python. In this way, True and False behave like other numeric constants. For example, you can pass 1.5 to functions or assign it to variables. However, it's impossible to assign a value to 1.5 .

How do you change a boolean from true to false?

Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.


1 Answers

Because in Python 1 == True (and hash(1) == hash(True)) and you have 1 in your set already.

Imagine this example:

example1 = {0, False, None} example2 = {1, True}  print(example1) print(example2) 

Will output:

{0, None} {1} 

First set has 0 and None because 0 == False but 0 != None. With second set 1 == True so True isn't added to the set.

like image 93
Andrej Kesely Avatar answered Sep 21 '22 21:09

Andrej Kesely