Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of "(1,) == 1," in Python?

People also ask

What is n == 1 in Python?

It means, "start at the end; count down to the beginning, stepping backwards one step at a time."

What does == to mean in Python?

In Python and many other programming languages, a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value . = is an assignment operator. == is an equality operator. x=10 y=20 z=20.

What is the meaning of i += 1 in Python?

i+=i means the i now adds its current value to its self so let's say i equals 10 using this += expression the value of i will now equal 20 because you just added 10 to its self. i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. 3rd January 2020, 3:15 AM.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.


This is just operator precedence. Your first

(1,) == 1,

groups like so:

((1,) == 1),

so builds a tuple with a single element from the result of comparing the one-element tuple 1, to the integer 1 for equality They're not equal, so you get the 1-tuple False, for a result.


Other answers have already shown you that the behaviour is due to operator precedence, as documented here.

I'm going to show you how to find the answer yourself next time you have a question similar to this. You can deconstruct how the expression parses using the ast module:

>>> import ast
>>> source_code = '(1,) == 1,'
>>> print(ast.dump(ast.parse(source_code), annotate_fields=False))
Module([Expr(Tuple([Compare(Tuple([Num(1)], Load()), [Eq()], [Num(1)])], Load()))])

From this we can see that the code gets parsed as Tim Peters explained:

Module([Expr(
    Tuple([
        Compare(
            Tuple([Num(1)], Load()), 
            [Eq()], 
            [Num(1)]
        )
    ], Load())
)])

When you do

>>> (1,) == 1,

it builds a tuple with the result from comparing the tuple (1,) with an integer and thus returning False.

Instead when you assign to variables, the two equal tuples are compared with each other.

You can try:

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