Sort Lists
Python is a powerful programming language that comes with many built-in functions and libraries. Lists are a fundamental built-in data type in Python, providing powerful tools to manage collections of items. Sorting a list is a common task in programming, and Python provides a simple and efficient way to sort lists using built-in functions. In this article, we will discuss the different methods available to sort lists in Python, including the built-in sorted() and sort() functions.
The sorted() Function
The sorted() function is a built-in Python function that returns a sorted list from an iterable object. The function can be used to sort any iterable object, including lists, tuples, and strings. The sorted() function creates a new sorted list and leaves the original list unchanged.
Sort a list of simple data in Python
fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
sorted_fruits = sorted(fruits)
print(sorted_fruits)Output:
['apple', 'banana', 'cherry', 'durian', 'elderberry']The sort() Function
The sort() function is a built-in Python method that sorts a list in place. Unlike the sorted() function, which returns a new sorted list, the sort() function modifies the original list directly and returns None. The sort() function sorts the list in ascending order by default but can be reversed to sort the list in descending order.
Sort a list in Python by modifying the original list
fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
fruits.sort()
print(fruits)Output:
['apple', 'banana', 'cherry', 'durian', 'elderberry']To sort the list in descending order, we can pass the argument reverse=True to the sort() function.
Sort a list in Python in descending order
fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
fruits.sort(reverse=True)
print(fruits)Output:
['elderberry', 'durian', 'cherry', 'banana', 'apple']Sorting Lists with Key Function
Sometimes, we may want to sort a list based on a specific criterion. For example, we may want to sort a list of tuples based on the second element of each tuple. In such cases, we can use the key argument to specify a function that returns the value to be sorted.
Sort a list of tuples in Python based on the second element of the tuple
fruits = [('apple', 10), ('banana', 5), ('cherry', 20), ('durian', 15), ('elderberry', 25)]
sorted_fruits = sorted(fruits, key=lambda x: x[1])
print(sorted_fruits)Output:
[('banana', 5), ('apple', 10), ('durian', 15), ('cherry', 20), ('elderberry', 25)]In the above example, we used a lambda function to sort the list of tuples based on the second element of each tuple.
Conclusion
Sorting lists is an essential task in programming, and Python provides a simple and efficient way to sort lists using built-in functions. In this article, we covered the two built-in functions in Python, sorted() and sort(), and how to sort a list based on a specific criterion.
Practice
What methods can you use to sort lists in Python?