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.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Sort Mixed List
# using sort() + comparator
  
# comparator function for sort
def mixs(num):
    try:
        ele = int(num)
        return (0, ele, '')
    except ValueError:
        return (1, num, '')
  
  
# initialize list 
test_list = [4, 'gfg', 2, 'best', 'is', 3]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Sort Mixed List
# using sort() + comparator
test_list.sort(key = mixs)
  
# printing result
print("List after mixed sorting : " + str(test_list))

chevron_right


Output :

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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Sort Mixed List
# using sorted() + key + lambda + isdigit()
  
# initialize list 
test_list = ['4', 'gfg', '2', 'best', 'is', '3']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Sort Mixed List
# using sorted() + key + lambda + isdigit()
res = sorted(test_list, key = lambda ele: (0, int(ele))
                        if ele.isdigit() else (1, ele))
  
# printing result
print("List after mixed sorting : " + str(res))

chevron_right


Output :

The original list : ['4', 'gfg', '2', 'best', 'is', '3']
List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.