Python Sort List Alphabetically

To sort a list of strings in alphabetical order in Python, you can use the sort method on the list. This method will sort the list in place, meaning that it will modify the original list and you won’t need to create a new list. You can also use the sorted function to sort a list. This function returns a new sorted list, without modifying the original list.

1. Quick Examples of Sorting List Alphabetically

If you are in a hurry, below are some quick examples of sorting lists in alphabetical order.


# Below are quick examples

# Example 1: Sort list by alphabetical order
technology = ['Java','Hadoop','Spark','Pandas','Pyspark','NumPy']
technology.sort()

# Example 2: Sort the list in reverse alphabetical order
technology.sort(reverse=True)

# Example 3: Sorts the array in ascending according to
sort_tech = sorted(technology)

2. Python Sort List Alphabetically

By using the list.sort() function you can order a list of stings in alphabetical order, it takes key and reverse as parameters, key is a function to specify the sorting criteria(s), reverse is a boolean value that specifies whether the list should be sorted in asc (False) or desc (True) order. The default is reverse=False.

Here is an example of how you can use the sort method to order a list of strings in alphabetical order.


# Sort the list in ascending order
technology = ['Java','Hadoop','Spark','Pandas','Pyspark','NumPy']
technology.sort()
print(technology)

# Output:
# ['Hadoop', 'Java', 'NumPy', 'Pandas', 'Pyspark', 'Spark']

3. Sort in Reverse Alphabetical Order

To sort a list of strings in reverse alphabetical order, you can use the sort() method with the reverse argument set its value to reverse=True.


# Sort the list in reverse alphabetical order
technology = ['Java','Hadoop','Spark','Pandas','Pyspark','NumPy']
technology.sort(reverse=True)
print(technology)

# Output:
# ['Spark', 'Pyspark', 'Pandas', 'NumPy', 'Java', 'Hadoop']

4. Use sorted()

The sorted() function in Python is used to sort a sequence (such as a list, tuple) in alphabetical order. The function returns a new sorted list, leaving the original sequence unchanged. Here, is an example.


technology = ['Java','Hadoop','Spark','Pandas','Pyspark','NumPy']

# Using sorted()
sort_tech = sorted(technology)
print(technology)
print(sort_tech)

# Output:
# ['Java', 'Hadoop', 'Spark', 'Pandas', 'Pyspark', 'NumPy']
# ['Hadoop', 'Java', 'NumPy', 'Pandas', 'Pyspark', 'Spark']

Conclusion

In this article, I have explained how to sort a list alphabetically in python, First, I have covered using list.sort() function and python built-in function sorted().

Happy Learning !!

Related Articles

References

Leave a Reply

You are currently viewing Python Sort List Alphabetically