-1

I'm trying to gauge which is more pythonic.

if any( ( ( i % 2 == 0 and i > 4 ) for i in range(10) ) ) :
   return

if any( [ ( i % 2 == 0 and i > 4 ) for i in range(10) ] ) :
   return

Would the generator expression form short circuit any faster than the list comp?

jxramos
  • 7,356
  • 6
  • 57
  • 105
  • 1
    It would be more efficent to use `if True` or immediately `return` in this case. – MSeifert Jul 03 '18 at 18:25
  • Sorry, I chose a trivial example just to demonstrate concretely with; my use case is not taken from such an expression. – jxramos Jul 03 '18 at 18:28
  • 2
    Note, it would be Pythonic to follow PEP8, which means, [no spaces immediately inside parentheses, brackets, or braces](https://www.python.org/dev/peps/pep-0008/?#whitespace-in-expressions-and-statements). Also, generator expressions, if they are the only argument, don't require parentheses! This is much nicer, no? `any((i % 2 == 0 and i > 4) for i in range(10))` – juanpa.arrivillaga Jul 03 '18 at 21:19

1 Answers1

3

Use a genexp.

The list comp will fully evaluate before running through any, while the genexp will not. any will short-circuit on the first True value, so you save yourself evaluations this way.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • That's what I was thinking, but I wasn't sure if `any` would wind up concocting a list anyways. I'm starting to appreciate more these genexp's and am slowly starting to push the code base I work on to use those in lieu of list comps and for loops when appropriate. – jxramos Jul 03 '18 at 18:30
  • @jxramos *generally* the genexp will be faster. The most common counterexample is `str.join` (because it ends up constructing a list anyway) – Adam Smith Jul 03 '18 at 18:31
  • 1
    @AdamSmith in my experience, *generally* list comps are faster unless there is short-circuiting behavior, or the final list would be large, something like >1,000,000. Try it with different size of n for `sum(i for i in range(n))` vs `sum([i for i in range(n)])`. The true advantage of genexp's is memory efficiency. On my machine, genexp version was not faster until around n == 5000000 – juanpa.arrivillaga Jul 03 '18 at 19:00