Python Program to sort a tuple of custom objects by properties


Let us now dive into what a custom object in python is. We know that python provides us with a lot of pre-defined datatypes which can be used to store various types of data. But there are times where we have to define custom datatypes that can store data that cannot be represented by built-in datatypes.

For this purpose, python provides us “classes”, these classes help us customize and create that is fit for our needs. A class can have data and function to implement some behavior. An example of implementing a class in python is as follows −

class TempClass:
   self.name = ""
   self.age = 0

Given above is an example of a class that has a name “TempClass” and stores the name and age with their default values being “” and 0 respectively. We use self to define that we are accessing values of a particular instance of a class and the dot ‘.’ Operator is used to access the elements of a class.

Now that we know what custom objects are in python, we will now see what do we mean by tuple of custom objects. When a tuple is made up of all elements being a custom object, class instances, then we say that we have a tuple of custom objects.

For the examples below, we will be considering a class that has name and age as its data members. And we will make a tuple containing the objects of this class only.

Using the sort() function

The sort() function is an inbuilt python function which takes the name of list, map, set or tuple as argument and sorts the data structure.

To sort a tuple using the sort function we will have to use the type conversion. The idea will be to store the class objects in an unsorted tuple, then use this tuple and create a list of names and sort it. Use this sorted list of names to sort the entire tuple by names.

Algorithm

Step 1 – Take the number of elements in the tuple as user input

Step 2 – Use the for loop to store the number of objects required, at each iteration input name and age and store a class object with the input values as its data elements.

Step 3 – Create a list called sortedNames, and iterate over the unsortedTuple and store all the name elements of each object in the sortedNames list

Step 4 – Use the sort function on sortedNames list, now we have a list that contains names in sorted order

Step 5 – Create a sortedTuple named tuple, iterate over the sortedNames list using the for loop

Step 6 – Use another nested for loop, to iterate over the unsortedTuple

Step 7 – Check whether the name part of the current object of tuple is the same as the name in the sortedNames list

Step 8 – If yes then store the current object in the sortedTuple list and break out of the inner loop

Step 9 – If no, then continue to the next object of unsorted tuple

Step 10 – Print the elements of sortedTuple

Example

Let us see an example for this –

class MyTuple:
   def __init__(self, name, age) -> None:
      self.name = name
      self.age = age
unsortedTuple =( MyTuple("Vijay",23) , MyTuple("Aman",27), MyTuple("Aastha",21) )
print("Tuple before sorting by names are : ")
for person in unsortedTuple:
   print(f"Name : {person.name} Age : {person.age}")
sortedTuple = sorted(unsortedTuple, key= lambda person: person.name)
print("Tuple after sorting by names are : ")
for person in sortedTuple:
   print(f"Name : {person.name} Age : {person.age}")

Output

Tuple before sorting by names are :
Name : Raj Age : 23
Name : Aman Age : 21
Name : Suraj Age : 26
Tuple after sorting by names are :
Name : Aman Age : 21
Name : Raj Age : 23
Name : Suraj Age : 26

Using the sorted() method with key attribute

Alternatively, we can also use the sorted method that is built-in method of python with the key attribute to sort the tuple by properties.

This function returns a sorted list of the specified iterable object. The key attribute takes in a function, usually a lambda function, and sort the iterable based on these keys.

Example

Let us see an example –

class MyTuple:
   def __init__(self, name, age) -> None:
      self.name = name
      self.age = age
unsortedTuple =( MyTuple("Vijay",23) , MyTuple("Aman",27), MyTuple("Aastha",21) )
print("Tuple before sorting by names are : ")
for person in unsortedTuple:
   print(f"Name : {person.name} Age : {person.age}")
sortedTuple = sorted(unsortedTuple, key= lambda person: person.name)
print("Tuple after sorting by names are : ")
for person in sortedTuple:
   print(f"Name : {person.name} Age : {person.age}")

Output

Tuple before sorting by names are :
Name : Vijay Age : 23
Name : Aman Age : 27
Name : Aastha Age : 21
Tuple after sorting by names are :
Name : Aastha Age : 21
Name : Aman Age : 27
Name : Vijay Age : 23

Conclusion

In this article, we saw what a custom object in python is, how we can implement is using classes. We also saw how we can make a tuple of custom objects and how we can make use of sort and sorted methods to sort it by properties.

Updated on: 20-Feb-2023

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements