jeudi 20 août 2020

Is There a Way for an If Statement to Return True if a Value is Equal to One of a List of Values Python

Is there a way to do something like this in python, where if a value is equal to one of a set of values, the if statement returns true (without using or and then replicating the first expression and the condition)?

li1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in num:
    if n == 2, 3, 5, 8:
        li2.append(n)

This was an example without list comprehension but I want to have something like this with list comprehension, considering the whole point of it is to make code shorter.

li = [int + 1 for int in range(10) if int == 2, 3, 5, 8]

But I haven't found anything that could do this. I know you can use or and do something like this,

li = [int + 1 for int in range(10) if int + 1 == 2 or int + 1 == 3 or int + 1 == 5 or int + 1 == 8]

but it just seems lengthy. I've tried a lot of things like using lists, tuples, range(), or (without copying the first expression and the condition), etc. It either just says invalid syntax or doesn't do the right thing. I don't really know how to phrase the question, so I can't use a google search.

If anyone knows whether or not this can be done, thank you in advance! :)

Aucun commentaire:

Enregistrer un commentaire