Say I have 2 variables x
and y
and I want to iterate over all the values in between without knowing whether x
or y
is greater:
if(x>y):
for i in range(y,x):
#Code
elif(x<y):
for i in range(x,y):
#Code
What is the Pythonic way to do this without all the if-else
conditions? The order does not matter descending or ascending will do, but a general answer would be great!
How about:
for i in range(min(x,y), max(x,y)):
...
Another way is to use sorted
with unpacking:
x, y = 10, 1
for i in range(*sorted([x,y])):
print(i)
Output:
1
2
3
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With