Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple equality in python suprises [closed]

Tags:

python

tuples

Didn’t understand why in Python :

>>> (1,1) == 1,1 

Returns

>>>  (False, 1) 

And the statement:

>>>  1,1 == (1,1)

Returns

>>> (1, False)

But

>>> (1,1) == (1,1) 

Returns

 >>> True 

Moreover

 >>> 1,1,1 == (1,1,1) 

Returns

>>> (1, 1, False) 

Could someone explain what happening?

like image 408
Элёржон Кимсанов Avatar asked Nov 20 '25 12:11

Элёржон Кимсанов


1 Answers

In the first example, Python is making a tuple of two things:

  • The expression: (1,1) == 1 (Which evaluates to False)
  • The integer: 1

Adding parentheses around the order in which actions are performed might help you understand the output:

(1,1) == 1,1

is the same thing as

((1,1) == 1), 1)

Here, (1,1) == 1) evaluates to False, so you get the output

(False, 1)

In the same way,

1,1 == (1,1)

translates to 1, (1 == (1,1)) which becomes

(1, False)

and

1,1,1 == (1,1,1)

translates to 1,1, (1 == (1,1,1)) which is

(1, 1, False)

In this example, Python is making a tuple of three things:

  • The two 1's
  • The expression: 1 == (1,1,1) (Which evaluates to False)
like image 113
krmogi Avatar answered Nov 23 '25 02:11

krmogi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!