Skip to main content

Sort List Alphanumerically

Every list has a sort() method. Unless you tell it otherwise, it arranges items alphanumerically in ascending order.

Example

Put strings in alphabetical order:

Prompt
Write a Python program that creates a list of fruits (orange, mango, kiwi, pineapple, banana). Sort the list alphabetically using the sort() method and print the result.
Output: complete Python program

Example

Put numbers in numerical order:

Prompt
Write a Python program that creates a list of numbers (100, 50, 65, 82, 23). Sort the list numerically using the sort() method and print the result.
Output: complete Python program

Sort Descending

For descending order, pass the keyword argument reverse = True.

Example

Sort strings in descending order:

Prompt
Write a Python program that creates a list of fruits (orange, mango, kiwi, pineapple, banana). Sort the list in descending order using sort(reverse=True) and print the result.
Output: complete Python program

Example

Sort numbers in descending order:

Prompt
Write a Python program that creates a list of numbers (100, 50, 65, 82, 23). Sort the list in descending order using sort(reverse=True) and print the result.
Output: complete Python program

Customize Sort Function

Sorting can also follow a rule of your own: pass a function with the keyword argument key = function.

That function returns a value for each item, and the items are arranged by those values, lowest first.

Example

Order the numbers by their distance from 50:

Prompt
Write a Python program that defines a function returning abs(n - 50). Create a list of numbers (100, 50, 65, 82, 23), sort it using the custom function as the key, and print the result.
Output: complete Python program

Case Insensitive Sort

Out of the box, sort() is case sensitive, so every capital letter comes before any lower case letter.

Example

A case-sensitive sort may surprise you:

Prompt
Write a Python program that creates a list (banana, Orange, Kiwi, cherry). Sort the list using the default case-sensitive sort() and print the result.
Output: complete Python program

Example

Ignore case while sorting the list:

Prompt
Write a Python program that creates a list (banana, Orange, Kiwi, cherry). Perform a case-insensitive sort using sort(key=str.lower) and print the result.
Output: complete Python program

Reverse Order

Sometimes you simply want the items flipped, whatever their alphabetical order.

That is what the reverse() method does: it turns the current order of the elements around.

Example

Flip the order of the items:

Prompt
Write a Python program that creates a list (banana, Orange, Kiwi, cherry). Reverse the order of the list items using the reverse() method and print the result.
Output: complete Python program