Python is a powerful programming language that comes with many built-in functions and libraries. One such library is the 'list' module, which provides powerful tools to manage lists in Python. 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.

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 function that sorts a list in place. Unlike the sorted() function, which returns a new sorted list, the sort() function modifies the original list. The sort() function sorts the list in ascending order by default but can be reversed to sort the list in descending order.

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.

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.

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 Your Knowledge

What methods can you use to sort lists in Python?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?