Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of iterating over ranges when order is not known

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!

like image 821
DuttaA Avatar asked Nov 29 '22 13:11

DuttaA


2 Answers

How about:

for i in range(min(x,y), max(x,y)):
    ...
like image 110
Florian H Avatar answered Dec 01 '22 01:12

Florian H


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
...
like image 40
Chris Avatar answered Dec 01 '22 01:12

Chris