Why does a Python "x in xyz" comparison not yield equality when it returns True by itself? [duplicate] - python-3.x

This question already has answers here:
Why does the expression 0 < 0 == 0 return False in Python?
(9 answers)
Closed 7 days ago.
The following comparisons produce True:
>>> '1' in '11'
True
>>> ('1' in '11') == True
True
And with the parentheses the other way, I get a TypeError:
>>> '1' in ('11' == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
So how do I get False with no parentheses?
>>> '1' in '11' == True
False

The Python manual says in and == are of equal precedence. Thus, they're evaluated from left to right by default, but there's also chaining to consider. The expression you put above ('1' in '11' == True) is actually being evaluated as...
('1' in '11') and ('11' == True)
which of course is False. If you don't know what chaining is, it's what allows you to do something like...
if 0 < a < 1:
in Python, and have that mean what you expect ("a is greater than 0 but less than 1").

It has nothing to do with precedence. In Python relational operators chain, and containment is considered a relational operator. Therefore:
'1' in '11' == True
is the same as:
('1' in '11') and ('11' == True)
which is false since True is not equal to "11".

Chaining allows you to write x < y < z, and mean x < y and y < z. Look at this interaction:
>>> (False == True) == False
True
>>> False == (True == False)
True
>>> False == True == False
False
>>>
So in your example, '1' in '11' == True is equivalent to ('1' in '11') and ('11' == True)

Related

Using Python3: how to get a boolean statement for numbers in a list being divisible by 3

I am running my code through an example set: [9,20,2,3]
I have been using the modulo operator (%) and my code is:
if index < len(the_list):
for m in the_list:
print(m)
if m % 3 == 0:
a = True
else:
a = False
return a
else:
return False
Args:
the_list (list): The input list
index (int): The index
Returns:
_type_: True: if the value is divisible by 3,
False: if the value is not divisible by 3,
False: if the index is invalid
One additional condition I must include is if the index position is larger than the length of the list to return False, but I believe I already have that properly integrated.
You can just use a list comprehension.
[(num%3 == 0) for num in myList]
here is a function that could help you :
def divisible_by_three(numbers):
for number in numbers:
if number % 3 == 0:
return True
else:
return False
This should work, just replace myList with your actual list
myList = [9,20,2,3]
finalList = []
for x in myList:
if x % 3 == 0:
finalList.append(True)
else:
finalList.append(False)
print(finalList)

Exercise in python is returning None

I need to write a recursive function that receives a list and a target element and returns True if the element is in the list and False, otherwise.
EXAMPLES:
busca ([1,2,3], 2) -> returns True
busca ([], 49) -> returns False
I can't use Python's "x in list" command.
I've developed code, but it returns None for some cases. For others, it works correctly.
def busca(lista, alvo):
if len(lista) == 0:
return False
if alvo == lista[0]:
return True
if len(lista) == 1:
return False
else:
nova = lista[1:]
busca(nova, alvo)
# busca([3, 2, 1], 3)
Your function returns None when it ends in the following condition:
else:
nova = lista[1:]
busca(nova, alvo) # even when this execution return True/False it's not returned by calling function
Did you mean?
else:
nova = lista[1:]
return busca(nova, alvo)
I don't understand why you return False when the length of the list is equal to 1. I mean
2 in [2] => True
despite
len([2]) => 1
and:
busca([2], 2) => True
This makes more sense to me:
def busca(lst, tgt):
if len(lst) !=0:
if lst[0] == tgt:
return True
else:
return busca(lst[1:], tgt)
else:
return False
Can you explain?

Python interpreter evaluates expression 4 < 5 to True. Why then does 4 < 5 == True return False?

Was messing around with values and concept in interpreter and hit a logic stumbling block as 4 < 5 is True but this output is not considered equal to == True?
In Python3: 4 < 5 == True is equivalent to 4 < 5 and 5 == True, which evaluates to False because 5 != True.
Note that < and == have the same precedence.
Doc for reference https://docs.python.org/3/reference/expressions.html#comparisons
From Python documentation
Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are
comparison operators, then a op1 b op2 c ... y opN z is equivalent to
a op1 b and b op2 c and ... y opN z, except that each expression is
evaluated at most once.
From this specification is 4 < 5 == True equal to 4 < 5 and 5 == True (and from operator precedence in Python it equals to (4 < 5) and (5 == True)) where 4 < 5 is True, but 5 == True is False. So True and False is False.
>>> 4<5
True
>>> 4<5 == True
False
>>> (4<5) == True
True
>>>
I hope this clears your doubt. 4<5 == True is evaluating as 4<5 and 5 == True which overall returns False as 4<5 is True, but, 5 == True is False. This is due to < and == having the same level of precedence.

Python - any() - Check if elements in list is

I'm working on a program where sometimes I have to check if
a list elements is greater or equal to 0. List elements are always integers.
a = [0]
In some cases, the list only contains one integer which is == 0:
In this case, I need True as the return value of this check.
I thought that I can use any() for this purpose.
print(any(i for i in a if i >= 0))
But any() returns False. However, if I extend the list any() returns True.
a = [0, 1]
print(any(i for i in a if i >= 0))
True
I found a workaround for this problem but I would like to know why
any() returns False as long as the list contains one single element.
for i in a:
if i >= 0:
print('True')
break;
You are filtering the input list, then asking any() to test the filtered values. For [0], the filtered sequence is still [0] (albeit as a generated sequence, not an actual list), and you are asking if any of those values are true. 0 is a false value, so any() returns false:
>>> a = [0]
>>> genexpr = (i for i in a if i >= 0)
>>> list(genexpr)
[0]
>>> bool(0)
False
>>> any(i for i in a if i >= 0)
False
Put the test at the front of the generator expression:
any(i >= 0 for i in a)
That expression doesn't filter, it instead produces a sequence of boolean values, False if the test doesn't pass, True if it does. For [0], that produces the sequence with a single True value, so any() returns True:
>>> genexpr = (i >= 0 for i in a)
>>> list(genexpr)
[True]
>>> any(i >= 0 for i in a)
True

code printing wrong answer

Write a function first_last6(nums) that takes a list of ints nums and returns True if 6 appears as either the first or last element in the list. The list will be of length 1 or more.
My code:
def first_last6(nums):
if nums[0] or nums[-1] == "6":
return True
else:
return False
It is not returning the right answer for this test:
print(first_last6([3, 2, 1]))
its suppose to be False, while it prints True.
The original test checks if nums[0] is True or if nums[-1] is 6, to check if either is 6, should use:
if nums[0] == 6 or nums[-1] == 6:
Your code should be like this:
def first_last6(nums):
if (nums[0] == 6) or (nums[-1] == 6):
return True
else:
return False
In your original code, you check if the first element of the list evaluates to True (bool(1) is True in python). Instead, check if it is equal 6. And you check if the last element of the list is "6", instead of checking for 6.
A test in the interactive interpreter:
>>> 6 == "6"
False
>>> 6 == 6
True
>>> bool(1)
True

Resources