For example, let's say that I have a range of "10-1," how can I express this to say [1 2 3 4 5 6 7 8 9 10]?
Asked
Active
Viewed 40 times
-3
-
Does this answer your question? [How to reverse a list?](https://stackoverflow.com/questions/3940128/how-to-reverse-a-list) – Simon Mar 03 '22 at 01:05
-
1We're not here to do your work for you ;) What have you tried? Why didn't it work? See [how to ask](https://stackoverflow.com/help/how-to-ask) for tips on asking questions suited for stackoverflow :) – dwb Mar 03 '22 at 01:06
-
Use the `range()` function, e.g. `list(range(1, 11))` – Barmar Mar 03 '22 at 01:07
-
1@Simon There's no list to reverse. – Barmar Mar 03 '22 at 01:07
-
Do you want "1-10" and 10-1" to both produce the same result? i.e. always in ascending order, disregard the order given? Anyway, this isn't hard, please post your own code attempt and where you got stuck. It can be solved in one or two lines. – smci Mar 03 '22 at 01:10
1 Answers
0
You can use split
to read the start and end, use int
to convert them into integers, and then use range
to return a desired list.
def range_to_list(s):
end, start = map(int, s.split('-'))
return list(range(start, end + 1))
print(range_to_list('10-1')) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Depending on your goal, list
might not be necessary.

j1-lee
- 13,764
- 3
- 14
- 26
-
Consider whether OP wants "1-10" and 10-1" to both produce the same result, i.e. always in ascending order, disregard the order given. – smci Mar 03 '22 at 01:11
-
1@smci That is not presented in the question (yet). Also the title says "backwards", so I assumed dealing with `'10-1'` would be enough. – j1-lee Mar 03 '22 at 01:12
-
1I know that. Your solution hardcodes the assumption that it's always "end-start". You can avoid that by using `max()`, `min()` or `sorted(..., reverse=True)` on the list `[int(x) for x in s.spit('-')]`. Before you extract `end, start`. – smci Mar 03 '22 at 01:15
-
1@smci Thanks, I am aware of that. I just didn't want to make the question more complex. An OP gets what they ask---it's their job to elaborate on what they want. If someone else generalize it and gets accepted, I would be fine with that. But thank you again for pointing it out. – j1-lee Mar 03 '22 at 01:18