top of page
  • Writer's pictureHarini Mallawaarachchi

Python Sorted(): What happens when sorting different types of elements

In this post, we will learn about the Python sorted() method and how it works for different variable types with the help of examples.


The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list.


Example 1: Sort list, string and tuple

# vowels list
py_list = ['e', 'a', 'u', 'o', 'i']
print(sorted(py_list))
# Output: ['a', 'e', 'i', 'o', 'u']
# vowels tuple
py_tuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(py_tuple))
# Output: ['a', 'e', 'i', 'o', 'u']
# vowels tuple
py_tuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(py_tuple))
# Output: ['a', 'e', 'i', 'o', 'u']

Example 2: Sort in descending order

# set
py_set = {'e', 'a', 'u', 'o', 'i'}
print(sorted(py_set, reverse=True))
# ['u', 'o', 'i', 'e', 'a']

# dictionary
py_dict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print(sorted(py_dict, reverse=True))
# ['u', 'o', 'i', 'e', 'a']

# frozen set
frozen_set = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(frozen_set, reverse=True))
# ['u', 'o', 'i', 'e', 'a']

Example 3: Sort the list using sorted() having a key function

# take the second element for sort

def take_second(elem):
    return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key
sorted_list = sorted(random, key=take_second)

# print list
print('Sorted list:', sorted_list)

#Output: Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

Example 4: Sorting with multiple keys

# Nested list of student's info in a Science Olympiad# List elements: (Student's Name, Marks out of 100, Age)

participant_list = [
    ('Alison', 50, 18),
    ('Terence', 75, 12),
    ('David', 75, 20),
    ('Jimmy', 90, 22),
    ('John', 45, 12)
]
def sorter(item):# Since highest marks first, least error = most marks
    error = 100 - item[1]
    age = item[2]
    return (error, age)


sorted_list = sorted(participant_list, key=sorter)
print(sorted_list)


[('Jimmy', 90, 22), ('Terence', 75, 12), ('David', 75, 20), ('Alison', 50, 18), ('John', 45, 12)]
4 views0 comments

Recent Posts

See All

Comments


bottom of page