1

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?

Ailurophile
  • 2,552
  • 7
  • 21
  • 46
  • Your second example (`[chr(i) for i in reversed(range(ord('P'),ord('H')))]`) will fail for the same reason your first one did - you're still telling it to count from P to H. I think you intended to count from H to P and then reverse it. – Kemp Apr 26 '21 at 09:17
  • I want to count from `P` to `H` – Ailurophile Apr 26 '21 at 09:27
  • Correct, and you can do that by counting from H to P and then reversing it.. – Kemp Apr 26 '21 at 15:38

2 Answers2

2

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)
    
iBug
  • 35,554
  • 7
  • 89
  • 134
0
ord('P') -> 80
ord('H') -> 72

so [chr(i) for i in range(ord('P'),ord('H'))] is simply [chr(i) for i in range(80,72)] and in range defualt increment value is 1.

since start value > end value and default step increment is 1, so this iterator is running resulting in an empty list.

you need to change the increment value from default to -1

[chr(i) for i in range(ord('P')-1,ord('H')-1,-1)]

output

['O', 'N', 'M', 'L', 'K', 'J', 'I', 'H']

 
sahasrara62
  • 10,069
  • 3
  • 29
  • 44