Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "in" and "==" confusion

Tags:

python

print('a' in 'aa')
print('a' in 'aa' == True)
print(('a' in 'aa') == True)
print('a' in ('aa' == True))

The output is

True
False
True
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print('a' in ('aa' == True))
TypeError: argument of type 'bool' is not iterable

If line 2 is neither line 3 nor line 4, then what is it? How does it get False?

like image 663
pete Avatar asked Nov 21 '18 18:11

pete


People also ask

What is difference between == and is in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.

Is there a difference between == and is?

== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.

Is there a .equals in Python?

Python has two operators for equality comparisons, “is” and “==” (equals).

What is the difference between identical and equal objects in Python?

The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.


2 Answers

According to Expressions

print('a' in 'aa' == True)

is evaluated as

'a' in 'aa' and 'aa' == True

which is False.

See

print("a" in "aa" and "aa" == True)

==> False

The rest is trivial - it helps to keep operator precedence in mind to figure them out.


Similar ones:

  • Multiple comparison operators in single statement
  • Why does the expression 0 < 0 == 0 return False in Python?

with different statements. I flagged for dupe but the UI is wonky - I answered non the less to explain why yours exactly printed what it did.

like image 185
Patrick Artner Avatar answered Sep 30 '22 19:09

Patrick Artner


Case 1 : it's simple the answers is True.

print('a' in 'aa')

Case 2 : This operation is evaluated as 'a' in 'aa' and 'aa' == True, so obviously it will return false.

print('a' in 'aa' == True)

Case 3: Now because we have () enclosing ('a' in 'aa') and the precedence of () is highest among all so first 'a' in 'aa' is evaluated as True and then True == True

print(('a' in 'aa') == True)

Case 4 : Same as above because of precedence of (), its evaluated as 'aa' == True, which will result in error as it tries to apply in on a non iterable that is bool value.

print('a' in ('aa' == True))
like image 33
Sanchit Kumar Avatar answered Sep 30 '22 19:09

Sanchit Kumar