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

How to Sort a List Alphabetically in Python?

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

Example:

`['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).

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

Try It Yourself:

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:

```lst = ['ab', 'Ac', 'ad']
lst.sort()
print(lst)

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

To ignore the capitalization, you can simply call the `x.lower()` method on each element `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:

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

Python List Sort Alphabetically Reverse

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

```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., `'c'` comes before `'d'`).

Example:

`['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:

```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 `'alice 100'` is placed before `'alice 20'`.

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

```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© 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 `list.sort()` method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional `key` argument by passing a function that returns a comparable value for each element in the list. With the optional Boolean `reverse` argument, you can switch from ascending (`reverse=False`) to descending order (`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.

https://www.sickgaming.net/blog/2020/03/...in-python/

 Possibly Related Threads… Thread Author Replies Views Last Post [Tut] How To Kill A Thread In Python? xSicKxBot 0 6 9 hours ago Last Post: xSicKxBot [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 11 10-16-2020, 10:30 PM Last Post: xSicKxBot [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM Last Post: xSicKxBot [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 18 10-09-2020, 06:13 PM Last Post: xSicKxBot [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 29 10-02-2020, 04:24 AM Last Post: xSicKxBot [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 31 10-01-2020, 02:21 AM Last Post: xSicKxBot [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 34 09-29-2020, 09:02 PM Last Post: xSicKxBot [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 37 09-28-2020, 02:36 AM Last Post: xSicKxBot [Tut] List Changes After Assignment — How to Clone or Copy It? xSicKxBot 0 35 09-27-2020, 12:14 AM Last Post: xSicKxBot [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 33 09-25-2020, 07:51 PM Last Post: xSicKxBot

Forum Jump:

Become a Patron!
 Upcoming Events

 Latest Threads News - This Week At Bungie – 10/22/2020 Last Post: xSicKxBot Today 02:24 PM » Replies: 0 » Views: 0 News - Why bringing Donkey Kong 64 into ... Last Post: xSicKxBot Today 02:23 PM » Replies: 0 » Views: 1 News - Build beautiful creatures in Jona... Last Post: xSicKxBot Today 02:23 PM » Replies: 0 » Views: 1 Mobile - Tactical shojo RPG, Illusion Co... Last Post: xSicKxBot Today 11:01 AM » Replies: 0 » Views: 2 Microsoft - 3 Teams features that help k... Last Post: xSicKxBot Today 11:01 AM » Replies: 0 » Views: 2 News - Review: GONNER2 – Another Way To ... Last Post: xSicKxBot Today 11:01 AM » Replies: 0 » Views: 2 News - Gallery: Lots Of Gorgeous Hyrule ... Last Post: xSicKxBot Today 11:01 AM » Replies: 0 » Views: 2 News - These Metal Gear Solid Air Jordan... Last Post: xSicKxBot Today 11:01 AM » Replies: 0 » Views: 3 [Tut] How To Kill A Thread In Python? Last Post: xSicKxBot Today 05:40 AM » Replies: 0 » Views: 6 (Indie Deal) FREE Ghost Sweeper, ? NBA 2... Last Post: xSicKxBot Today 05:40 AM » Replies: 0 » Views: 6