Sort List in Python using sorted()

You can sort a list in ascending or descending order using sorted() builtin function. sorted() method does not modify the original list, but returns a new list with sorted elements, where the elements are from the original list.

Programs

sorted() – Sort List in Ascending Order

In the following program, we take a list of integers, and sort them in ascending order using sorted() function.

Pass the list as argument to sorted() function, and pass no other parameters.

main.py

#initialize list
nums = [21, 28, 14, 96, 84, 65, 74, 31]

#sort list
sortedList = sorted(nums)

#print sorted list
print(sortedList)

Output

[14, 21, 28, 31, 65, 74, 84, 96]

sorted() – Sort List in Descending Order

In the following program, we take a list of integers, and sort them in descending order using sorted() function.

For sorted() function to sort elements in descending order, pass reverse=True as argument.

main.py

#initialize list
nums = [21, 28, 14, 96, 84, 65, 74, 31]

#sort list
sortedList = sorted(nums, reverse=True)

#print sorted list
print(sortedList)

Output

[96, 84, 74, 65, 31, 28, 21, 14]

Conclusion

In this Python Tutorial, we learned how to sort a list in Python using sorted() builtin function, in ascending or descending order.