Sort mixed list in Python
Sometimes, while working with Python, we can have a problem in which we need to sort a particular list which has mixed data types. That it contains integers and strings and we need to sort each of them accordingly. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using
sort() + comparator
This problem can be solved using sort functionality provided by Python. We can construct our own custom comparator to complete the task of mixed sort.
The original list : [4, 'gfg', 2, 'best', 'is', 3] List after mixed sorting : [2, 3, 4, 'best', 'gfg', 'is']
Method #2 : Using
sorted() + key + lambda + isdigit()
The combination of above functionalities can also be used to achieve solution to this problem. In this, we just sort the list using sorted() using key functionality using lambda function to segregate digits using isdigit().
The original list : ['4', 'gfg', '2', 'best', 'is', '3'] List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course