Linking operators using the keyword 'and'

I do the following:

if ycoords[0] > 0 and ycoords[1] > 0 and ycoords[2] > 0: # do stuff 

Can you shorten this code by doing something like:

 if (ycoords[0] and ycoords[1] and ycoords[2]) > 0: # do stuff 
+6
source share
3 answers

Yes, you can use all :

 if all(x > 0 for x in ycoords): 

or ycoords[:3] if ycoords has more than 3 elements.

+9
source

No, you can just use min for parsing:

 if min(ycoords[0],ycoords[1],ycoords[2]) > 0: # do stuff 

and given that ycoords has exactly three elements, even shorter:

 if min(*ycoords) > 0: #do stuff 

you can here, as @Tagc says, omit the asterisk ( * ):

 if min(ycoords) > 0: #do stuff 

but this will lead to some overhead.

Another option is to use all :

 if all(x > 0 for x in [ycoords[0],ycoords[1],ycoords[2]]): # do stuff 

or again if ycoords contains only these three elements:

 if all(x > 0 for x in ycoords): # do stuff 
+3
source

Something that is not intuitive is that and :

"neither and nor or do not limit the value and type, they return to False and True, but rather we will return the last evaluated argument"

Just open a python terminal and do:

 >> 4 and 3 3 

Why is this important to consider?

You might think that:

 (ycoords[0] and ycoords[1] and ycoords[2]) > 0 

is equivalent to:

 ycoords[0] > 0 and ycoords[1] > 0 and ycoords[2] > 0 

which is equivalent to:

 (bool(ycoords[0]) and bool(ycoords[1]) and bool(ycoords[2])) > 0 

but instead, it is equivalent to:

 ycoords[2] > 0 

So, be careful because the interpreter does not do what you think.

+1
source

Source: https://habr.com/ru/post/1014251/


All Articles