Best way to find a range of integers when you don't know if the start or end is greater in Python

Viewed 42

I'm playing AdventOfCode Day 5 (https://adventofcode.com/2021/day/5) and one of the things I like about it is that it let's you think about how to solve problems better.

Today:

I want to get a range between two integer numbers that includes both numbers. It it not known in advance which number is higher.

This code works, but it's ugly and hard to read.

list(range(a, b + (1 if a < b else -1), 1 if a < b else -1))

returns for a=4, b=7:

[4, 5, 6, 7]

and for a=7, b=4:

[7, 6, 5, 4]

Is there an easier, Pythonic way of getting the range without using any new (temporary) variables and writing a lot of code?

1 Answers

This may be easier to understand and read, which is what "Pythonic" means to me:

if a <= b:
    r = range(a, b + 1)
else
    r = range(a, b - 1, -1)
Related