Python – Sort a List by Factor count

When it is required to sort a list by factor count, a method is defined that uses list comprehension and modulus operator along with ‘len’ method to determine the output.


Below is a demonstration of the same −

def factor_count(element):
   return len([element for index in range(1, element) if element % index == 0])

my_list = [121, 1120, 13540, 221, 1400]

print("The list is :")


print("The result is :")


The list is :
[121, 1120, 13540, 221, 1400]
The result is :
[121, 221, 13540, 1120, 1400]


  • A method named ‘factor_count’ is defined that takes element of list as a parameter, and returns output.

  • Outside the method, a list is defined and displayed on the console.

  • The list is sorted using ‘sort’ method and the key is specified as the previously defined method.

  • This is the output that is displayed on the console.