Simple sorting of a list of objects by a specific property using Python | by Gibson Tang | Towards Data Science

In my rudimentary experiments with Python and Data modeling where I have to import data into my Jupyter notebook. I thought of sorting and it occurred to me how do you sort a list of objects using a specific instance variable, such as name. For example, I have a list of car objects which consist of name and price.
So I want to produce a list where the results are sorted in alphabetical order using the name of the car like so. And I didn’t want to use any libraries, so no import for me then.
Googling didn’t return me much information as the results returned plenty of information on sorting of numbers, some results regarding sorting of words, and no satisfactory result of sorting of a word which is part of an instance variable. So I decided to have a crack at it. Python is not something that I am required to do in my day job. But I do use Python for the occasional scripting when there is a need for it. So I thought that I would have a crack at it.
So this is how I would have approached the problem and my example code is shown below
First, I would declare a class of cars and create a list to insert these objects
class cars:    def __init__(self, name, price):          self.name = name        self.price = price unsorted_cars = []unsorted_cars.append(cars('Ford', 20000))unsorted_cars.append(cars('Volvo', 50000))unsorted_cars.append(cars('BMW', 24000)) unsorted_cars.append(cars('Toyota', 15000)) unsorted_cars.append(cars('Kia', 12000)) unsorted_cars.append(cars('Audi', 40000)) unsorted_cars.append(cars('Tesla', 30000))
And since I want to sort the list by the name of the card, I created an empty list and put in the car names into that list and use the standard sort function to sort the list
sorted_car_name = []for car in unsorted_cars: 	sorted_car_name.append(car.name)sorted_car_name.sort()
This will then return a sorted list of car names in alphabetical order. Finally, now that I have the list of sorted names. I can use this as a reference to get the list of sort car objects using this double for loop to iterate through the unsorted_cars list and use the name instance variable in each car object to compare against each word in the sorted_car_name list and then insert it into a new empty list sorted_car_list if there is a match
sorted_car = []for sort_car in sorted_car_name:  	for unsorted_car in unsorted_cars:		if unsorted_car.name == sort_car:			sorted_car.append(unsorted_car)			break
sorted_car_list now will then have the final list of cars sorted by the car name in alphabetical order as shown in table 2 above. Do note that this method is not very efficient due to the double for loop where we loop through the list of cart objects in unsorted_cars and then loop through each word in sorted_car_name and do a comparison to see if there is a match and then we insert that unsorted_car object into the sorted_car list.
You can download the sample Python code here. To run the code, just go to your command line and type ‘python python_sort_sample.py’ and it will print out the list of unsorted cars and the final sorted cars. I hope this can be helpful to any Python folk out there.
A friend of mind, Ruiwen, just pointed out to me that Python has a sorted() function that can be used. The sorted() function takes in a list of objects, the key to sort by and returns the sorted list. This function uses Lamba which creates an anonymous function. So to sort our unsorted list of car names, we use
result_list = sorted(unsorted_cars, key=lambda cars: cars.name)for car in result_list:        print(car.name + " and price is " + str(car.price))
So, by passing in the list of unsorted cars, and the anonymous function and the attribute to sort by, which is the name of the car. We will get the sorted list in result_list. This is a much better way of sorting, although the usage of the Lamba veers your Python code into the functional programming paradigm.
I have updated my sample code and included the sorted() method here in this gist https://gist.github.com/gibtang/83f9681b525908900ec4b490992f032d
Some related links to the sorted functionhttps://julien.danjou.info/python-functional-programming-lambda/https://docs.python.org/3/howto/sorting.htmlhttps://www.w3schools.com/python/ref_func_sorted.asp