0
How to compare all list items and arrange them in ascending order?
For example: I have list list = [2,6,8,4,3,2,9,15,0] I want to compare all the elements and arrange them in ascending order And I should get in input list = [0, 2, 2, 3, 4, 6, 8, 9, 15]
2 Respuestas
+ 5
Sorting in python can be done in 2 ways:
# please dont use the name list as a variable or object name. This can lead to unexpected behaviour !!!
lst = [2,6,8,4,3,2,9,15,0] # original list
print(lst)
# sorting in place - changes original list in defined order
lst.sort()
print(lst)
# output: [0, 2, 2, 3, 4, 6, 8, 9, 15]
# sorting not in place - list keeps in original order, new list with sorted items will be created
list = [2,6,8,4,3,2,9,15,0]
res = sorted(lst)
print(res)
# output : [0, 2, 2, 3, 4, 6, 8, 9, 15]
Both versions can have an optional key argument to do user defined sorting. Therefor a lambda function is used.
+ 2
It is called sorting.
https://www.sololearn.com/learn/774/?ref=app
You can learn here about the different sorting algorithms.