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.
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.
5
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.
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
How is a sequence is possible to use range
X = 2
if X in range(1, 5):
print("ok")
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)?
Credits to @Anderson Carlos Woss for his reply.
Browser other questions tagged python python-3.x boolean
You are not signed in. Login or sign up in order to post.
What if
X = True
? xD– Woss
If you use "or", it enters the same way using True :P
– Wictor Chaves
Python equals php right, 1 is True is the same thing
– Wictor Chaves
Almost that, in Python the
bool
inherits fromint
, gettingTrue
beingint(1)
andFalse
beingint(0)
. The problem only occurs if the list of values has 0 and/or 1.– Woss
it’s to do so
if X in [1, 2, 3, 4] and type(X) != bool:
, but it gets ugly :P– Wictor Chaves
Got it, living and learning :)
– Wictor Chaves
If you use a tuple instead of the list you can save a few bytes per
if
.– Giovanni Nunes
Edited response :)
– Wictor Chaves