How to Sort Words Alphabetically in Python

Problem Formulation and Solution Overview

In this article, you’ll learn how to sort words alphabetically in Python.

To make it more fun, we have the following running scenario:

Some English sayings, also known as Tongue-Twisters, are fun to try and say quickly. They are also used to improve non-English speaking individuals and small children’s fluency and pronunciation of the English language.

Imagine how challenging tongue twisters would be if sorted in alphabetical order!


πŸ’¬ Question: How would we write code to sort a string in alphabetical order?

We can accomplish this task by one of the following options:


Method 1: Use split() and sort()

This method uses Python’s built-in string library to reference split() and sort() to display the words in ascending alphabetical order.

twister = 'how much wood would a woodchuck chuck if a woodchuck could chuck wood?'.lower().split()
twister.sort()
print(twister)

Above declares a tongue twister, converts the entire string to lowercase (lower()) and breaks it apart (split()) by default, on the space (' ') character. The results save to twister in a List format. If output to the terminal, the following displays.

['How', 'much', 'wood', 'would', 'a', 'woodchuck', 'chuck', 'if', 'a', 'woodchuck', 'could', 'chuck', 'wood?']

The following line sorts twister (sort()) in ascending alphabetical order. If output to the terminal, the following would display.

['a', 'a', 'chuck', 'chuck', 'could', 'how', 'if', 'much', 'wood', 'wood?', 'woodchuck', 'woodchuck', 'would']

Method 2: Use split(), sorted() and join()

This method uses Python’s built-in string library to reference split() and sorted() to display the words in descending alphabetical order.

twister = 'I scream, you scream, we all scream for ice cream!'.lower()
twister = ' '.join(sorted(twister.split(), reverse=True)) 
print(twister)

Above declares a tongue twister, then converts the string to lowercase (lower()). The results save to twister in a List format. If output to the terminal, the following would display.

['i', 'scream,', 'you', 'scream,', 'we', 'all', 'scream', 'for', 'ice', 'cream!']

The following line breaks it apart (split()) by default, on the space (' ') character. Then, twister is sorted (sorted()) in descending alphabetical order (reverse=True).

The words are combined using the join() function, saved to twister and output to the terminal.

['you', 'we', 'scream,', 'scream,', 'scream', 'ice', 'i', 'for', 'cream!', 'all']

Method 3: Use Bubble Sort Algorithm

This method uses the famous Bubble Sort Algorithm. This function accepts a List and loops through each element, comparing two (2) values, the current element value and the next element value. The greater element floats to the top, and the loop continues until the List is sorted.

twister = 'Which wristwatches are Swiss wristwatches?'.lower().split()

def bubblesort(lst):
    for passesLeft in range(len(lst)-1, 0, -1):
        for i in range(passesLeft):
            if lst[i] > lst[i + 1]:
                lst[i], lst[i + 1] = lst[i + 1], lst[i]
    return ' '.join(lst)

print(bubblesort(twister)) 

Above declares a tongue twister, converts the entire string to lowercase (lower()) and breaks it apart (split()) by default, on the space (' ') character. The results save to twister in a List format. If output to the terminal, the following displays.

['which', 'wristwatches', 'are', 'swiss', 'wristwatches?']

Next, the bubblesort() function is declared and accepts one (1) argument, an iterable List. An explanation of this code is outlined above.

However, we modified the code slightly to return a new string containing the sorted List values.

The bubblesort() function is then called and passed twister as an argument. The results are output to the terminal.

are swiss which wristwatches wristwatches?

Method 4: Use sort_values()

This function imports the Pandas Library to reference the sort_values() function. This function sorts column(s) in a DataFrame.

To run this code error-free, install the required library. Click here for installation instructions.

To follow along, click here to download the finxters.csv file. Move this file to the current working directory.

import pandas as pd 

df = pd.read_csv('finxters.csv', skip_blank_lines=True, usecols=['FID', 'Username', 'Rank'])
rank_sort = df.sort_values(by=["Rank"], ascending=True)
print(rank_sort)

Above, imports the Pandas library.

Then, the finxter.csv file is read in, omitting blank lines, selecting the three (3) stated columns and saving to df.

Next, sort is applied to the Rank column, which contains the words pertaining to a user’s achievement level. The DataFrame (df) is sorted based on this column and the results save to rank_sort and output to the terminal.

Below a snippet of the results displays.

FIDUsernameRank
030022145wildone92Authority
453002481Moon_Star2Authority
930022450Gar_manAuthority
430022359AliceMAuthority
243002328Wall_2021Authority
493002573jJonesingAuthority
473002521KerrStreetAutodidact

Summary

These four (4) methods of sorting words alphabetically should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd