This question already has answers here:
Python. Will TWO condition checked, If `ONE == True`? [duplicate]
(3 answers)
Closed 5 years ago.
I have a multi-part boolean expression in a piece of python code, part of which involves a call to a random number generator and evaluating an expoenential of a sum of a 2d array. Since this is buried deep in nested loops I want to avoid checking that last part if at all possible, since it's computationally expensive.
if self.B == 0 or (np.sign(self.B) == -sign) or (np.random.rand() < np.exp(-2*sign*self.B*np.sum(cluster))):
do stuff
If either of the first two expression are true, will the random number generator still be called? Or is it guaranteed to evaluate those parts in order and stop once it finds one that is true?
I can always make it explicit by breaking it up, but it seems like something I should probably know anyway.
In if A or B, B is only evaluated if A is false.
This concept is called short circuiting, and you can read a little about it here.
The idea is that you go from left to right until a result is determined. Once that's the case, you stop.
Related
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 7 months ago.
After working through some toy examples, I could see that it's possible to emulate the ternary operator of "c" condition?value_if_true:value_if_false in Python using condition and value_if_true or value_if_false.
I would like to know if it works in all cases and if it is better or worse than using value_if_true if condition else value_if_false.
It's strictly worse: the conditional expression was added to the language specifically to avoid the problem with using ... and ... or ... incorrectly.
# 0 is falsy
>>> True and 0 or 5
5
>>> 0 if True else 5
0
PEP-308 references "FAQ 4.16" for other workarounds to the problems with and/or, though I can no longer track down what FAQ is being referred to, but it was eventually decided that a dedicated conditional expression was preferable.
For example, one could write
(True and [0] or [3])[0]
to ensure that the true-result is truthy, so that the false-result isn't returned. The false-result has to be adjusted as well so that regardless of what result is produced, it can be indexed to finally provide the intended result.
This question already has answers here:
How to get all possible combinations of a list’s elements?
(32 answers)
How to calculate a Cartesian product of a list with itself [duplicate]
(2 answers)
Closed 2 years ago.
In my code below, 'single' refers to a finite list. I then need to get all possible pairs from this list; however, the program didn't finish executing.
After messing around with some print statements, for some reason, despite 'single' having a finite number of elements (13122; I checked with len()) the for loop was running forever, until I but a break statement in which forcibly ends the loop when the index gets too high. Initially I thought this was because I was referencing over 'single' twice; however, even when I replaced 'single' with copy.deepcopy(single), the same problem occurred, and my fix no longer worked.
If it is of any help, the elements of 'single' are themselves lists.
'''
for index1, i in enumerate(single):
for index2, j in enumerate(single):
return_list.append([i,j])
if (index1 > length):
break
'''
By iterating through the list twice, you are having to append to that return_list 13122*13122=172186884 times. That will take ages, there are much better and more performant ways of calculating that list if that is really what you want to do (will take up an enormous amount of memory).
Take a look at itertools.combinations.
list(itertools.combinations(single, 2))
This question already has answers here:
How do I check if a list is empty?
(27 answers)
Closed 2 years ago.
Before getting to the main question, I should first ask: When you're trying to check if a list is empty in Python, is there any case where the four cases below would yield a different boolean?
if not []
if not len([])
if len([]) == 0
if len([]) is 0
If not, which is the fastest way to check for this boolean and why? - i.e. what exactly is happening under the hood for each case? The difference may be trivial but I'm curious as to how these might differ during execution.
if not array
This is the most idiomatic way to check it. Caveat: it will not work on other iterables, e.g. numpy arrays.
if not len(array)
Equivalent to the expression above, but is not as idiomatic. It will work on numpy arrays, but still might fail on other iterables with custom __len__ (nonexistent threat, to be clear)
if len(array) == 0
Same as above, but eliminates the nonexistent threat from custom iterables
if len(array) is 0
DANGER ZONE: it will work in CPython because of implementation details, but generally there is no guarantee it won't break in the future, or that it'll work on other Python implementations. Avoid at all costs.
This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
if statement without a condition
(3 answers)
Closed 2 years ago.
Apologies if this is a straightforward thing, I’m just not having luck getting answers online (and if this isn’t a good place to post).
I’ve been trying to improve my Python, and I’ve been trying to make sense of some code for a Neural Network/Natural Language Processing package. I came across this:
if args.encoder_layers_to_keep:
args.encoder_layers = len(args.encoder_layers_to_keep.split(","))
I haven’t come across an if statement with an expression like this. There’s no comparison between variables or anything. My only guess is that it returns a true or false value and works with that but I’m really not sure.
For reference, here’s the full script - https://github.com/pytorch/fairseq/blob/master/fairseq/models/transformer.py
I’d appreciate any help with this.
Thanks,
Justin
Empty sequences (e.g., lists, tuples, strings) evaluate to False. Non-empty sequences evaluate to True.
args.encoder_layers_to_keep seems to be a string variable. An empty string "" evaluates to False, and a non-empty string evaluates to True.
You can prove this to yourself by using the builtin function bool to convert to a boolean. Try bool("") and bool("foobar").
This is suggested in the Python style guide (PEP8):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
if not seq:
if seq:
# Wrong:
if len(seq):
if not len(seq):
This question already has answers here:
and / or operators return value [duplicate]
(4 answers)
Closed 6 years ago.
I didn't see this question already, and I'm curious to find out what's going on here. Please forgive me if it's been asked and answered already.
While taking a course on Udacity, the instructor quickly mentioned a line he used in the Python code that looked like this:
n = n and int(n)
He said that it's basically equivalent to:
if n:
n = int(n)
The statement works just as he described, but I'm curious about how it works, because I've never seen this kind of construction in Python before. Can anyone explain what it is about using and in this casting assignment that makes it work this way?
Also, having never seen it before, I would have no idea that this statement is functioning the way it is, which makes me think that it may not be the most Pythonic way to write this code. Is this a widely known and accepted shortcut, or should I generally stick with the explicit if statement when I need to do something like this?
Edit: Ok, initial question is a duplicate, and has been clearly answered elsewhere, and now here as well. Thanks to all for those answers. One final question I have: which way should I prefer in my code (aka which is more Pythonic)?
condition1 and condition2.
condition2 is executed only if the condition1 passes. If n resolves to a True in Boolean context then n is converted to int by the statement int(n) and assigned to n
In context of Boolean operations the following are considered as false
- False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and
frozensets)
From doc
This is caused by python's lazy evaluation (or more accurately, short-circuit boolean expressions), see:
https://docs.python.org/2/reference/expressions.html#boolean-operations :
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Also see the answer to:
Does Python evaluate if's conditions lazily?