Home » Sorting a list in Python

Sorting a list in Python

Using sort() method

By using sort method the original list gets modified. As you see below the list named numbers got modified instead of creating or returning new list. Use list_name.sort() to sort the list in ascending order. If you want to sort in descending order then use list_name.sort(reverse=True) .

#consider the below list for example
numbers = [7,3,9,1,6,2,0]

#sorting the list of number using sort() method

print('Sorted List:',numbers)

Sorted List : [0, 1, 2, 3, 6, 7, 9]

Using sorted() method

You can also sort the list using sorted() method which takes an iterable as an argument and returns a new list. Use should use another variable to hold the returned list.

old_list = [2,4,1,7,3,9]
#sorting and storing in new variable
new_list = sorted(old_list)


[1, 2, 3, 4, 7, 9]

Also Read:
Add Two Numbers – Python
Append element in list Python
Access Jetson Device via Remote Desktop
Hello world program in Python
Difference between ++i and i++
Assertion failed: mode == “constant” && value == 0.f && “This version of TensorRT only supports constant 0 padding!”
Copy file from host VM to Docker container
Copying files from Docker container to host VM
Filter Docker images