Skip to content
Home » How to Sort a List Using the Sorted Function

How to Sort a List Using the Sorted Function

Spread the love

You can sort a list or any other sequence, or rather loop over a sequence in sorted order. To do that you can use the sorted function. If you use this function, the original sequence doesn’t get sorted. If you need descending order, you can just combine the two functions: reversed and sorted:

important_dates = [1776, 1066, 1789, 1939, 1848, 1543]

print("Important dates in chronological order:")
for date in sorted(important_dates):
    print(date)

print()
print("Important dates in reversed order:")
for date in reversed(sorted(important_dates)):
    print(date)

Here’s the output that you will get when you run the code above.

Important dates in chronological order:
1066
1543
1776
1789
1848
1939

Important dates in reversed order:
1939
1848
1789
1776
1543
1066

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version:


Spread the love

Leave a Reply