python list sort

python list have sort method. so, I will introduce how to use the method with example code.

the method declaration is like below

sort(*, key=None, reverse=False)
 if you don't pass any parameter, "sort" method will compare items with only < comparison operation.

"key" parameter has to be function object. through this parameter, you can define the key value to be compared.

if you use lambda expression, you can make the key parameter easier. but if I introduce it in this page, it is out of range of this subject. so I will introduce lambda later.

"reverse" define the order of sorting items. simply, the evaluation of comparison is reversed or not.


list1 = [2,3,5,1,6,7]
list2 = [(1,2),(4,3),(2,1),(3,4)]

def comp1(item):
    return item%3

def comp2(item):
    return item[1]

list1.sort()
print(list1)

list1.sort(reverse=True)
print(list1)

list1.sort(key=comp1) # items iwll be sorted by the remainder of 3
print(list1)

list2.sort(key=comp2) # items will be sorted by second element of tuple.
print(list2)


Comments

Popular posts from this blog

making menubar and menu on QML

QSizePolicy Fixed example in pyside2

let's start QML programming with PySide2