-1

Just thought I would specify in the title, because I have found the latter all over the internet, but not the former. I am curious how to get a conditional that contains a list comprehension working in python. Specifically, I am curious about how to do something like the following:

if (abs(value - any_x)) > 100 for any_x in x:

Essentially, I want the program to proceed if the absolute value of the difference between the value and any value in the x array is greater than 100. But the syntax as it stands is incorrect. What exactly am I missing? Thanks and best regards,

-AA

  • You don't *need a list comprehension*. You aren't creating a `list`, which is what list comprehensions are for. A naive loop would be better, or you can use a generator expression and `any`, so `any(abs(value - e) > 100 for e in x)` – juanpa.arrivillaga Feb 13 '20 at 18:31

3 Answers3

3

Use any:

if any(abs(value - any_x) > 100 for any_x in x):
    ...

Don't use a list comprehension here as any will return True on the first True value it finds. Thus providing it a generator is the most efficient method as it will be lazily evaluated.

Jab
  • 26,853
  • 21
  • 75
  • 114
1

You can use any.

if any(abs(value - any_x) > 100 for any_x in x):
totalhack
  • 2,298
  • 17
  • 23
0

Pretty simple,

True in [abs(k-value)>100 for k in x]
kpie
  • 9,588
  • 5
  • 28
  • 50
  • 1
    Inefficient though. If the list contains a million items and the first item satisfies the condition it will still unnecessarily check all items. – 001 Feb 13 '20 at 18:31