Simple create alphabet and reverse them in Python using number


It’s suddenly pop-out on my head which what the one-liner solution for creating alphabet (A-Z) in Python and reversed them. Then, the first thing is using built-in python function like ord() and chr(). Then, I can use list comprehension to make it compact.

Example:

1
[chr(x) for x in range(ord("a"), ord("z") + 1)]


This will showing result:

1
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]

Then, how to reverse? It easy as:

1
[chr(x) for x in range(ord("a"), ord("z") + 1)][::-1]

Which give me correct result:

1
[‘z’, ‘y’, ‘x’, ‘w’, ‘v’, ‘u’, ‘t’, ‘s’, ‘r’, ‘q’, ‘p’, ‘o’, ‘n’, ‘m’, ‘l’, ‘k’, ‘j’, ‘i’, ‘h’, ‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘b’, ‘a’]

I wrote this to kill the time of waiting washing machine 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.