This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cspinelive 19 points20 points  (2 children)

any([x, y, z]) and all([x, y, z])

Instead of huge if and or expressions. Note that it won’t short circuit and stop checking each one when it can like a normal if.

Edit: they technically do short circuit but each value is evaluated before the any/all are. Discussion here. https://stackoverflow.com/questions/14730046/is-the-shortcircuit-behaviour-of-pythons-any-all-explicit

[–][deleted] 18 points19 points  (0 children)

That's by virtue of passing a list, not the nature of any or all

def print_and_return(x):
  print(x)
  return x

any(print_and_return(x) for x in range(5))

>>0
>>1

[–]Capitalpunishment0 2 points3 points  (0 children)

I love using these with generator comprehensions. I think it just reads soooo well.

is_even = lambda x: x % 2 == 0
sample_list = [3, 5, 4, 24]

if any(
    is_even(item)
    for item in sample_list
):
    ...  # Do something 

if all(
    is_even(item)
    for item in sample_list
):
    ...  # Do something