-1

I have the following list and variable:

x = [1,2,17,4,5,7,11]
v = 18

and I want (in a single if statement) to search in the list to check if it contains an item that if we subtract "or any other operation" it from v variable will equal to one "as example".

For the above example, the if statement will yield True since we have the item 18 (18-17=1).

Can we do that in a single if statement (without using a separate loop) with python ?

Minions
  • 5,104
  • 5
  • 50
  • 91

2 Answers2

3

You can get a list of answers out with a list comprehension that uses if statement:

x = [1,2,18,4,5,7,11]
v = 17
answers = [i for i in x if i-v==1]
print(answers) # [18]
baduker
  • 19,152
  • 9
  • 33
  • 56
yoyoyoyo123
  • 2,362
  • 2
  • 22
  • 36
3

The correct answer to your question is already in comments, but assuming you tried to make your example more minimal to hide a more complicated question (one where the operation for which you substituted subtraction is not invertible), you can do this in Python with the any function and a list comprehension:

x = [1,2,18,4,5,7,11]
v = 17
if any([a - v == 1 for a in x]):
    print("Found it!")
Mees de Vries
  • 639
  • 3
  • 24