- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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(my_list) my_list.sort(key=factor_count) print("The result is :") print(my_list)
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.
- Python – Sort Matrix by Palindrome count
- Python – Sort by a particular digit count in elements
- Python – Sort by Units Digit in a List
- Python program to Sort Strings by Punctuation count
- Python – Sort String list by K character frequency
- Python – Sort by Rear Character in Strings List
- Python Program to sort rows of a matrix by custom element count
- Python program to sort a list of tuples by second Item
- Sort list of tuples by specific ordering in Python
- Python – Sort Dictionary List by Key’s ith Index value
- Ways to sort list of dictionaries by values in Python
- How can I sort one list by values from another list in Python?
- Python – Sort given list of strings by numeric part of string
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Python program to Sort a List of Strings by the Number of Unique Characters