How to Sort Elements in a List in Python?

Estimated read time 2 min read

To sort elements in a list in Python, you can use the built-in sort() function or the sorted() function. The sort() function sorts the list in place, while the sorted() function returns a new sorted list.

Here’s an example using the sort() function:

my_list = [4, 2, 8, 1, 3, 9, 6]
my_list.sort()
print(my_list)  # Output: [1, 2, 3, 4, 6, 8, 9]

And here’s an example using the sorted() function:

my_list = [4, 2, 8, 1, 3, 9, 6]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 2, 3, 4, 6, 8, 9]

Both functions can also take optional arguments to modify how the sorting is performed. For example, you can use the reverse=True argument to sort the list in descending order:

my_list = [4, 2, 8, 1, 3, 9, 6]
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 8, 6, 4, 3, 2, 1]

sorted_list = sorted(my_list, reverse=True)
print(sorted_list)  # Output: [9, 8, 6, 4, 3, 2, 1]

You can also use the key argument to specify a function to determine the sorting key for each element. For example, you can sort a list of strings by their lengths:

my_list = ["apple", "banana", "cherry", "date", "elderberry"]
my_list.sort(key=len)
print(my_list)  # Output: ['date', 'apple', 'cherry', 'banana', 'elderberry']

sorted_list = sorted(my_list, key=len)
print(sorted_list)  # Output: ['date', 'apple', 'cherry', 'banana', 'elderberry']

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply