1

This is probably really simple but I can't figure it out.

I have a bunch of lists and I want to call certain lists if they are in the range equal to a value x and any number between x-5 and x +5. i.e. x-5,x-4,x-3,x-2,x-1,x,x+1,x+2,x+3,x+4 and x+5.

At the moment I have

if sum(listname[i])==x:

if sum(listname[i])==x-1:

if sum(listname[i])==x-2:

etc

How can I do it so that it is combined in one "if" function.

I've been thinking on the lines of something like:

if sum(listname[i])==x-5>=x>=x+5:

or

if sum(listname[i])==x or x-1 or x-2 ".. etc":

but neither work.

Can anybody shine some light on this?

2
  • This is pretty theoretical, can you make a minimal reproducible example with complete sample input and output? Also, your terminology is a bit shaky. if is not a function and you can't call lists. (We should be able to understand what you want with the MCVE, though.)
    – timgeb
    Commented Nov 24, 2018 at 23:17
  • 1
    Try this if x-5 <= sum(listname[i]) <= x+5:. If x is a real number x-5 cannot be superior to x+5
    – Wariored
    Commented Nov 24, 2018 at 23:22

4 Answers 4

3

A scenario like if sum(listname[i])==x or x-1 or x-2 ".. etc": (which is not valid python) is usually solved with if value in range(start, stop, step):

So you would write:

if sum(listname[i) in range(x-2, x):
    # Code for this case here...
2

Do you simply mean

if x-5 <= sum(listname[i]) <= x+5:
    ...
    ...
2
  • 1
    You might want to exchange >= with <=. Otherwise good answer.
    – a_guest
    Commented Nov 24, 2018 at 23:26
  • x-5 cannot be superior to x+5
    – Wariored
    Commented Nov 24, 2018 at 23:27
0

It looks like you want to check if the sum of the list is between x - 5 and x + 5. To put it in one if statement is simply:

s = sum(listname[i])
if s >= x - 5 and s <= x + 5:
  # do stuff
0

From what I understand from your question. You what to check that whether sum(listname[i]) is between (x-5, x+5)

You can do this in a single if assuming x is a possitive value:

if (sum(listname[i]) >= (x - 5)) and (sum(listname[i]) <= (x+5))