in over multiple lists [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
I was recently confused by this
if 2 in ([1,2] or [3,4]) : print(True)
else: print(False)
#prints True
or is a boolean operator so how can it be applied to lists?
why does it work the same as if 2 in [1,2] or [3,4]?

Use any()
print(any(2 in x for x in [[1, 2], [3, 4]]))
or is operates on any types, not just booleans. It returns the leftmost operand that's truthy, or False if none of the operands are truthy. So ([1, 2] or [3, 4]) is equivalent to [1, 2] because any non-empty list is truthy.
In general, operators don't automatically distribute in programming languages like they do in English. x in (a or b) is not the same as x in a or x in b. Programming languages evaluate expressions recursively, so x in (a or b) is roughly equivalent to:
temp = a or b
x in temp

Both statement are different.
In first case python will first run 2 in [1,4] its False so now it will check for bool([1,3]) and its True so it prints 1.
But for second case what happening is first ([1,4] or [1,3]) is executing and this return first non-empty list. And so it will return [1,4] but 2 is not in list so nothing gets printed.
Its all about execution order.
Look at two more examples. Specially last example. ([1,4] or [2,4]) will return [1,4] and 2 is not in [1,4]. Now it will not check in second list [2,4]. If that's you want this is not the right way to do it. Use any
>>> if 2 in [1,4] or [1,3]: # True
... print(1)
...
1
>>> if 2 in ([1,4] or [1,3]): # False
... print(1)
...
>>> if 2 in [1,4] or []: # False
... print(1)
...
>>> if 2 in ([1,4] or [2,4]): # False!!
... print(1)
...

Related

or operator does not returns boolean type [duplicate]

This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
enter image description here
i'm now working on if statements
this is my code
a = [1,2,3]
print(4 or 5 in a)
and the outcome is 4 not False
this code returns what i have expected
a = [1,2,3]
print((4 or 5) in a)
I can't understand how or operator works
why the return is integer..? not True or False
If there are multiple conditions in an if statement, if the first statement is correct, it doesn't check the second statement. Since 4 is true, it doesn't check if 5 is in the variable a or not. Therefore, it returns the value 4 and not False
In this case you have expression written incorrectly and as a result it evaluates the way it does. What you should have written was:
>>> a = [2, 1, 4]
>>> 4 in a or 5 in a
Out[18]: True
In your case the expression evaluates only the condition 4 or 5 which evaluates to 4 as the first truthy value.
>>> 4 or 5 in a
Out[27]: 4
>>> 4 or 5
Out[28]: 4
In fact, variable a is completely skipped here and not evaluated at all. We can do the same but using variable b that has never been defined in this session and we get 4 instead of UnboundLocalError:
>>> 4 or 5 in b
Out[31]: 4
Similarly we can test this behaviour. When you compare two truthy values the result is always the first one the interpreter encounters.
>>> 'a' or 'b'
Out[29]: 'a'
>>> 'd' or 'a'
Out[30]: 'd'
I suggest reading docs on boolean operators in Python to get a better understanding of what's happening (for example, here). It can get confusing.

Return bool value in pythonic way comparing within list? [duplicate]

This question already has answers here:
Python: determine if all items of a list are the same item [duplicate]
(7 answers)
Check if all elements in a list are identical
(30 answers)
Closed 5 years ago.
I am comparing fist element of list vs all the elements of list. If False is there I need to return false or if all are true, I need to return True. Currently I am doing this with if-else. is there any pythonic way to return bool value
def checker(inp):
_compare = [ _==inp[0] for _ in inp]
return False if False in _compare else True
lst = [5, 5, 5]
lst2 = [5, 5, 6]
# Case 1
level = checker(inp=lst)
print(level)
True
# Case 2
level2 = checker(inp=lst2)
print(level2)
False
Any pythonic way to achieve this
return False if False in _compare else True
False in _compare is already a boolean so
return False not in _compare
is the best way to do it.
but looking wider:
_==inp[0] for _ in inp
should be
return all(x==inp[0] for x in inp)
so it returns False if one value is False
This solution works even if the items aren't hashable.
if all the numbers in list are same I want to return True if not False
The most straight forward way:
return len(set(inp)) == 1
This does require the values to be hashable, but simple numbers are.
Your problem is identical to the question "I need to check if all elements in my list are identical", since both are true for exactly the same cases. So you could also solve it like this:
def checker(inp):
return len(set(inp)) == 1
If that is the most pythonic way to go about it .. I don't know.
edit: alternative in case of unhashable items:
def checker(inp):
return not [True for i in range(len(inp) - 1)) if [inp[i] != inp[i+1]]

Trying to understand a simple feature about 'and' command in python. Can anyone clarify it? [duplicate]

This question already has answers here:
and / or operators return value [duplicate]
(4 answers)
What does "variable or 0" mean in python?
(4 answers)
Closed 7 years ago.
In Python, if I write
z = 1 and 2
print z
Then it yields "2".
But if I write
z = 0 and 2
print z
Now, it yields "0".
It may not be much important in real life problem, but I'm trying to understand the logic here.
0, [], "" are all false-ish (they are treated as False in a python condition). and returns the first false-ish value or the last one. This is called short-circuit evaluation. That's why in one case it returns 2 (the last) and in the other it returns 0 (the false-ish).
In fact if you think about the logic operation, you can short-circuit this behaviour:
x and y (with x false-ish) -> x
x and y (with x true-ish) -> y
When plugged into a condition it will evaluate as:
In the first case it evaluates the boolean result of x which is False. This is the correct result for the and operation, since False and y = False for any y.
In the second case it evaluates the boolean value of y. Since x is True, the result of and should be False when y is False and True when y is True (it reflects the value of y).
c = a and b
is the same as
if a:
c=b
else:
c=a
I think more interesting is or:
c = a or b
is the same as
if a:
c=a
else:
c=b
Note also that if a: is a short way of if bool(a):. bool returns False for this objects/values:
None, 0, False, "", [], tuple(), dict(), set()
As you can see, they are all somehow empty...
The and operator in python short circuits. That is: it only evaluates enough operands (from left to right) as are necessary to determine whether the outcome is True or False. The result of and is False so in the second case, where 0 evaluates to False, and returns 0, but as 1 is True, the second operand must also be evaluated and returned.
0 is treated as False and anything above zero is treated as True so z = 1 and 2 sets z equal to 2 and z = 0 and 2 is 0 because it evaluates to False.

Is there a difference between "if not x" and "if x is None"? [duplicate]

This question already has answers here:
Difference between "if x" and "if x is not None"
(5 answers)
if A vs if A is not None:
(13 answers)
Evaluation of boolean expressions in Python
(2 answers)
Closed 8 years ago.
I have:
x = None
Many references I have found so far do the "null" check in the following fashion:
if x is None:
...
(for example, this question).
Whereas throughout my code I have:
if not x:
...
What I am doing currently works as predicted (returns true), but I'd like to know if there are any use cases where it is optimal to perform the check the way it is done in the first example.
Apologies if this is very obvious or if the question has been asked before - I couldn't find the answer to this specific Q on the site.
not x will also return True for everything that evaluates to False in a boolean context. Some examples:
>>> x = ()
>>> not x
True
>>> x = []
>>> not x
True
>>> x = ''
>>> not x
True
>>> x = 0
>>> not x
True
>>> x is None
False
So if your code should act differently when x is None as opposed to x being an empty list, tuple, string, the number zero, ... then use x == None or x is None instead of not x.

Is it better to use "is" or "==" for number comparison in Python? [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 1 year ago.
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python?
Examples:
>>> a = 1
>>> a is 1
True
>>> a == 1
True
>>> a is 0
False
>>> a == 0
False
Use ==.
Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.
Others have answered your question, but I'll go into a little bit more detail:
Python's is compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to == in Java). So, there are some times when using is makes sense - the most common one being checking for None. Eg, foo is None. But, in general, it isn't what you want.
==, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:
>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False
And this is true because classes can define the method they use to test for equality:
>>> class AlwaysEqual(object):
... def __eq__(self, other):
... return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True
But they cannot define the method used for testing identity (ie, they can't override is).
>>> a = 255556
>>> a == 255556
True
>>> a is 255556
False
I think that should answer it ;-)
The reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is, they are not the same.
That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.
>>> a = 2104214124
>>> b = 2104214124
>>> a == b
True
>>> a is b
False
So you should always use == to compare numbers.
== is what you want, "is" just happens to work on your examples.
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==

Categories

Resources