The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:s:sorting

sorting

Sorting elements, usually inside a list. the Suffix .sort() can sort a list in-place. To get a new sortable without destroying the original, use sorted(list_or_whatever_you_want_to_sort)

see:

Python has an in-built sorting function:

>>> mylist = [1,5,6,8,99,3,2,5,7,77,8,88,0,33]
>>> mylist.sort()
>>> mylist
[0, 1, 2, 3, 5, 5, 6, 7, 8, 8, 33, 77, 88, 99]

You can also sort reverse the elements in a list or sort in reverse order:

>>> mylist = [1,5,6,8,99,3,2,5,7,77,8,88,0,33]
>>> mylist.reverse()
>>> mylist
[33, 0, 88, 8, 77, 7, 5, 2, 3, 99, 8, 6, 5, 1]
>>> mylist.sort(reverse=True)
>>> mylist
[99, 88, 77, 33, 8, 8, 7, 6, 5, 5, 3, 2, 1, 0]
>>> 

using sorted(), sorting by key

Sorted() works faster than .sort() and works also with other objects, not only with lists. Sorted accepts a callable (a function) as argument to get the key for the sort order.

examples:

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
sorted(student_tuples, key=lambda student: student[2])   # sort by age

This works also with a class and attributes:

class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age
    def __repr__(self):
        return repr((self.name, self.grade, self.age))

student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
sorted(student_objects, key=lambda student: student.age)   # sort by age

en/glossary/s/sorting.txt · Last modified: 2020/12/04 07:54 by horst