How to generate a sorted list in Python?


The sort method on lists in python uses the given class's gt and lt operators to compare. Most built in classes already has these operators implemented so it automatically gives you sorted list. You can use it as follows:

words = ["Hello", "World", "Foo", "Bar", "Nope"]
numbers = [100, 12, 52, 354, 25]
words.sort()
numbers.sort()

print(words)
print(numbers)

This will give the output:

['Bar', 'Foo', 'Hello', 'Nope', 'World']
[12, 25, 52, 100, 354]

If you don't want the input list to be sorted in place, you can use the sorted function to do so. For example,

words = ["Hello", "World", "Foo", "Bar", "Nope"]
sorted_words = sorted(words)

print(words)
print(sorted_words)

This will give the output:

["Hello", "World", "Foo", "Bar", "Nope"]
['Bar', 'Foo', 'Hello', 'Nope', 'World']

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 17-Jun-2020

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements