+91 81900 98289

Sort Lists

This Sort Lists lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

sorted returns a new list and leaves the original alone. sort changes the list you already have.

reverse=True sorts from high to low. key= chooses the value used for the comparison.

Example 1: Start here

sorted(marks) does not change marks. marks.sort does.

marks = [82, 71, 90] # a list; the values stay in this order print(sorted(marks)) # a new list, sorted marks.sort(reverse=True) # sort this list in place print(marks)

Example 2: Sort numbers

sort changes the list itself and puts the smallest number first.

scores = [82, 60, 91] # a list; the values stay in this order scores.sort() # sort this list in place print(scores)

Example 3: Sort descending

reverse=True puts the largest number first.

scores = [82, 60, 91] # a list; the values stay in this order scores.sort(reverse=True) # sort this list in place print(scores)

Example 4: Sort without changing the original

sorted returns a new list. The original scores stay in the old order.

scores = [82, 60, 91] # a list; the values stay in this order print(sorted(scores)) # a new list, sorted print(scores)
sorted(marks) does not change marks. marks.sort does.
Call Now 81900 98289