Sorting list of strings in lexicographic order

Wizard picture Wizard · May 20, 2018 · Viewed 16.9k times · Source

I want to print the words in lexicographic order. I thought sorted() arranges the words in this way. I have also tried .sort() which returns the same order. Or am I missing something with what lexicographic order really is?

Code:

a_list = ['Zrhregegrydb', 'cygzRFWDWBdvF']
for word in sorted(a_list):
    print(word)

Output:

# Zrhregegrydb
# cygzRFWDWBdvF

Desired Output:

# cygzRFWDWBdvF
# Zrhregegrydb

Answer

Tané Tachyon picture Tané Tachyon · May 20, 2018

This is because the ASCII value of upper-case letters is smaller than lower-case. If you want your sort to ignore case you can do this, for example:

for word in sorted(a_list, key=str.lower):