Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Sort a List Alphabetically in Python?
1
How to Sort a List Alphabetically in Python?

Problem: Given a list of strings. Sort the list of strings in alphabetical order.

Example:

Code:
['Frank', 'Alice', 'Bob'] --> ['Alice', 'Bob', 'Frank']

Solution: Use the list.sort() method without argument to solve the list in lexicographical order which is a generalization of alphabetical order (also applies to the second, third, … characters).

Code:
lst = ['Frank', 'Alice', 'Bob'] lst.sort() print(lst) # ['Alice', 'Bob', 'Frank']

Try It Yourself:

https://repl.it/@finxter/sortalphabet?li...HiPAailwCE

Python List Sort Alphabetically Case Insensitive

The problem with the default list.sort() or sorted(list) method is that they consider capitalization. This way, it can lead to strange sortings like this:

Code:
lst = ['ab', 'Ac', 'ad'] lst.sort() print(lst) # ['Ac', 'ab', 'ad']

Intuitively, you would expect the string
Code:
'ab'
to occur before
Code:
'Ac'
, right?

To ignore the capitalization, you can simply call the
Code:
x.lower()
method on each element
Code:
x
before sorting the list.

However, my preferred method is to use the key argument to accomplish the same thing in a single line of code:

Code:
lst = ['ab', 'Ac', 'ad'] lst.sort(key=lambda x: x.lower()) print(lst) # ['ab', 'Ac', 'ad']

If you like one-liners, you’ll love my new book “Python One-Liners” with NoStarch Press (Amazon Link).

Python List Sort Alphabetically Reverse

You can reverse the order of the list by using the reverse keyword. Set
Code:
reverse=False
to sort in ascending order and set
Code:
reverse=True
to sort in descending order.

Code:
lst = ['Frank', 'Alice', 'Bob'] lst.sort(reverse=False) print(lst) # ['Alice', 'Bob', 'Frank'] lst.sort(reverse=True) print(lst) # ['Frank', 'Bob', 'Alice']
Python List Sort Alphabetically and Numerically

Problem: You’ve got a list of strings. Each strings contains a number. You want the numbers to sort numerically (e.g. 100 comes after 20, not before) but the characters to sort alphabetically (e.g.,
Code:
'c'
comes before
Code:
'd'
).

Example:

Code:
['alice 100', 'alice 20', 'bob 99'] --> ['alice 20', 'alice 100', 'bob 99'

Naive Solution (doesn’t work): Use the list.sort() method to sort the list alphabetically:

Code:
lst = ['alice 100', 'alice 20', 'bob 99'] lst.sort() print(lst) # ['alice 100', 'alice 20', 'bob 99']

Because the number 100 comes before 20 in an alphabetical order, the string
Code:
'alice 100'
is placed before
Code:
'alice 20'
.

Solution: I found this code on StackOverflow that nicely demonstrates how to do this:

Code:
import re def sorted_nicely(l): """ Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] l.sort(key = alphanum_key) lst = ['alice 100', 'alice 20', 'bob 99'] sorted_nicely(lst) print(lst) # ['alice 20', 'alice 100', 'bob 99']

The idea is to differentiate characters and numbers and use them as the basis of comparison for the sort routine.

Where to Go From Here?

The
Code:
list.sort()
method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional
Code:
key
argument by passing a function that returns a comparable value for each element in the list. With the optional Boolean
Code:
reverse
argument, you can switch from ascending (
Code:
reverse=False
) to descending order (
Code:
reverse=True
).


If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: