How to simplify the if command in python?

Asked

Viewed 512 times

3

Is there any way I can simplify this line of code in Python:

if X = 1 or X = 2 or X = 3 or X = 4:

I was trying this way:

if X = {1 or 2 or 3 or 4}:

But trying like that makes a mistake.

2 answers

5


Using Array

You can use "in", see this example

X = 2
if X in [1, 2, 3, 4]: 
    print("ok")

I represented the values using an array [1, 2, 3, 4], so I use "in" to check if the value of "X" is inside the array.

Using Tupla

Execute

Following our friend’s tip Giovanni Nunes

X = 2
if X in (1, 2, 3, 4): 
    print("ok")

Using a tuple instead of the list saves you a few bytes per if

Execute

Using Range

How is a sequence is possible to use range

X = 2
if X in range(1, 5): 
    print("ok")

Execute

  • What if X = True? xD

  • If you use "or", it enters the same way using True :P

  • Python equals php right, 1 is True is the same thing

  • Almost that, in Python the bool inherits from int, getting True being int(1) and False being int(0). The problem only occurs if the list of values has 0 and/or 1.

  • it’s to do so if X in [1, 2, 3, 4] and type(X) != bool:, but it gets ugly :P

  • Got it, living and learning :)

  • If you use a tuple instead of the list you can save a few bytes per if.

  • Edited response :)

Show 3 more comments

3

As seen in the @Wictor Chaves reply, you can use lists or tuples, but I’ll bring you one more option: sets (set).

A set stores similar values to each other and, by definition, unique within the set. Not to mention that the access to the values and the verification if it has a certain value tends to be optimized in relation to the list and tuple.

Rewriting your code would look like this:

if X in {1, 2, 3, 4}:

You can read more about sets in this question here: How to access the elements of a set (set)?

  • 1

    Credits to @Anderson Carlos Woss for his reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.