In this tutorial, we will be covering how to sort a list alphabetically in Python. Sorting data is a common task in programming and Python makes this task even simpler with its in-built functions.
Python provides a handy .sort() method that you can take advantage of to sort any list. This method changes the order of a list it is called on. Let’s delve in and see how this works.
Step 1: Starting with a Basic List
In Python, a list is a data structure that holds an ordered collection of items, which can be of any type. Here is a simple list:
1 |
fruits = ['pear', 'banana', 'kiwi', 'apple', 'mango'] |
We have a list called fruits containing five elements. They are not arranged in order, alphabetically.
Step 2: Using the .sort() Method
To sort the fruits list alphabetically, we just need to call the .sort() method on the list:
1 |
fruits.sort() |
When you print out the list now, you will get:
1 |
print(fruits) |
Output:
1 |
['apple', 'banana', 'kiwi', 'mango', 'pear'] |
The list has been sorted in ascending order, which is alphabetically in this case.
Step 3: Using sorted() Function
You can also use Python’s in-built function sorted(), which sorts the elements of a given iterable in a specific order (either ascending or descending) and returns the sorted iterable as a list:
1 2 3 4 |
fruits = ['pear', 'banana', 'kiwi', 'apple', 'mango'] sorted_list = sorted(fruits) print(sorted_list) |
Output:
1 |
['apple', 'banana', 'kiwi', 'mango', 'pear'] |
The main difference here is that the original list is not changed when using the sorted() function. It returns a new list that is sorted, rather than sorting the existing list.
Sample Code
1 2 3 4 5 6 7 8 9 10 |
fruits = ['pear', 'banana', 'kiwi', 'apple', 'mango'] # Using .sort() fruits.sort() print("Sorted list with .sort: ", fruits) # Using sorted() fruits = ['pear', 'banana', 'kiwi', 'apple', 'mango'] sorted_list = sorted(fruits) print("Sorted list with sorted(): ", sorted_list) |
Conclusion
And there you go! Now you know how to sort a list alphabetically in Python using the .sort() method and sorted() function. These are great tools that you can use to easily sort your data in Python. Remember that .sort() modifies the list it is called on, while sorted() creates a new sorted list and leaves the original unaltered.