How To Sort A Set In Python
Sorting Lists in Python
How to use sort() and sorted() to sort lists in Python
In this tutorial, we will await at how to sort lists using sort() and sorted() based on different criteria in python.
Sorting a List
There are two means to sort a list. We can either use the sort() method or the sorted() role. The sort() method is a listing method and thus can only be used on lists. The sorted() office works on any iterable.
sort() method
The sort() method is a list method that modifies the listing in-place and returns None. In other words, the sort() method modifies or changes the list information technology is called on, and does not create a new listing.
The sort() method has 2 optional parameters: the key parameter and contrary parameter. The key parameter takes in a function that takes a single argument and returns a key to utilize for sorting. By default, the sort() method will sort a list of numbers past their values and a listing of strings alphabetically. The reverse parameter accepts a boolean value of True or Imitation. The default value for opposite is False, significant it sorts in ascending order. To sort in descending order, we would fix reverse=True. These parameters will brand much more sense as we look at some examples below.
Sorting a List of Numbers
Let's say that we take a listing of numbers and we desire to sort it in ascending order.
num_list = [1,-5,3,-9,25,x] num_list.sort() print(num_list)
# [-9,-5,1,iii,10,25]
Then nosotros have a list of numbers, or num_list. Nosotros phone call the sort() method on this listing. Notice how we didn't pass in a value for the key parameter. Thus, it just sorted this list of numbers by their actual values. And since nosotros didn't set reverse = True, it sorted in ascending social club. The sort() method modified our num_list.
What if we want to sort our list based on the absolute values of the numbers? That is when we would need to use the key parameter. The key parameter takes in a part that takes a unmarried argument and returns a key to use for sorting.
num_list = [1,-five,3,-9,25,10] def absolute_value(num):
return abs(num) num_list.sort(fundamental = absolute_value) print(num_list)
# [1,iii,-5,-9,ten,25]
We defined a function, absolute_value, that takes in a number and returns its accented value. We and so passed this function in every bit the statement for the key parameter of the sort() method. Thus, it runs each element or number of num_list through the accented value function before it makes the comparing. As a event, the absolute values of the numbers are used to sort this listing in ascending club (since contrary is set to False by default).
Using a lambda expression
Nosotros could take passed in a lambda expression instead for the fundamental parameter every bit follows:
num_list.sort(fundamental = lambda num: abs(num))
For more information well-nigh lambda functions:
Recollect that the sort() method returns None. Thus, if we ready the output, or return value, of the sort() method to a new variable, we get None as follows:
new_list = num_list.sort(key = absolute_value) impress(new_list)
# None
Using built-in functions
Instead of writing our ain absolute_value function as we did higher up, we could have just passed in the python congenital-in abs() part for the key parameter as follows:
num_list.sort(key = abs)
sorted() office
The sorted() function can accept three parameters: the iterable, the key, and reverse. In other words, the sort() method only works on lists, but the sorted() function can work on any iterable, such every bit lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged.
Allow's sort num_list once more using the accented values merely using the sorted() function instead:
num_list = [one,-5,iii,-nine,25,10] new_list = sorted(num_list, key = abs) print(new_list)
# [one,iii,-5,-ix,ten,25] print(num_list)
# [1,-5,3,-9,25,10]
We pass in the iterable, num_list, to the sorted() function, along with the built-in abs office to the cardinal parameter. We set the output of the sorted() office to a new variable, new_list. Note how num_list is unaltered since the sorted() part does not alter the iterable it acts on.
Note: No matter what iterable is passed in to the sorted() function, it always returns a listing.
Sorting a Listing of Tuples
Permit's say that we have a listing of tuples. Each chemical element of the listing is a tuple that contains three elements: the proper noun, age, and salary.
list_of_tuples = [
('john', 27, 45000),
('jane', 25, 65000),
('beth', 31, 70000)
]
We can sort this listing alphabetically, past age, or by bacon. We can specify which nosotros desire to use with the key parameter.
To sort by age, we can use the post-obit code:
sorted_age_list = sorted(list_of_tuples, key = lambda person: person[1]) print(sorted_age_list)
# [('jane', 25, 65000), ('john', 27, 45000), ('beth', 31, 70000)]
Each element of the list_of_tuples is passed in to the lambda office as the person parameter. The chemical element at alphabetize 1 of each tuple is returned. That is the value that is used to sort the listing, which is the age.
To sort the name alphabetically, we can do so without passing a central at all since by default the kickoff element of each tuple is what is compared (and think, by default, strings are sorted alphabetically):
sorted_name_list = sorted(list_of_tuples) print(sorted_name_list)
# [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]
All the same, we can specify that nosotros desire to sort by the beginning element of each tuple as follows:
sorted_name_list = sorted(list_of_tuples, key = lambda person: person[0]) print(sorted_name_list)
# [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]
Recall that nosotros can assign a lambda expression to a variable (similar to using the def keyword to ascertain a function). Thus, we can organize the lambda expressions based on the criteria they utilise to sort the list:
name = lambda person: person[0]
age = lambda person: person[1]
salary = lambda person: person[two] # sort by name
sorted(list_of_tuples, key = name) # sort by historic period
sorted(list_of_tuples, key = age) # sort by bacon
sorted(list_of_tuples, cardinal = salary)
Conclusion
In this tutorial, we compared the sort() method and sorted() office when sorting a list based on different criteria. We learned how the sort() method modifies the original list, and the sorted() function returns a new list.
Source: https://towardsdatascience.com/sorting-lists-in-python-31477e0817d8
0 Response to "How To Sort A Set In Python"
Post a Comment