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
Here’s the video version:
Spread the love