I do realize this has already been addressed here (e.g., Is it possible to make a letter range in python?). Nevertheless, I hope this question was different.
The below code gives the range between any two alphabets
[chr(i) for i in range(ord('H'),ord('P'))]
Output
['H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
For the range of alphabets in reversed order, using reversed()
returns the empty list
[chr(i) for i in range(ord('P'),ord('H'))]
# or
[chr(i) for i in reversed(range(ord('P'),ord('H')))]
Output
[]
Expected output
['O', 'N', 'M', 'L', 'K', 'J', 'I', 'H']
How to get a letter range in reversed order in Python?
ord('P')
is greater than ord('H')
, so range(...)
makes an empty range.
To get a reverse letter list, do either of the following:
Make a forward list and apply reverse()
:
reversed( range(ord('H'), ord('P')) )
Use the 3rd parameter to range()
:
range(ord('P'), ord('H'), -1)