Skip to content
Advertisement

How to edit this simple function to correctly sort letters and words in list alphabetically (Python)?

The objective is to take a list of strings, sort the letters in each string, and then sort the full list. We want to modify the list in place (so, use sort() rather than sorted()).

My function:

def string_lst(lst):
        return lst.sort()

So, this means I would expect:

string_lst(["bdb", "acb"])

To return "abc", "bbd"

This doesn’t work though. Can anyone suggest how to amend this function to achieve the desired output?

Advertisement

Answer

Let’s divide the problem into 2 parts: sorting a string and sorting a list of strings.

The first part: There is no direct method for sorting strings in python. But we can use sorted, which accepts iterable as an argument and returns sorted list of items of iterable:

>>> s = 'bace'   
>>> sorted(a)
['a','b','c','e']             

We can join that list to get sorted string:

>>>sorted_a = ''.join(sorted(a))
>>>sorted_a
'abce'

So we can write this for the first part:

def sort_list(list_of_strings):
    for i in range(len(list_of_strings)):
        list_of_strings[i] = ''.join(sorted(list_of_strings[i]))

The second part is easy, there is sort method for sorting lists and we will use that. Final result:

def sort_list(list_of_strings):
    for i in range(len(list_of_strings)):
        list_of_strings[i] = ''.join(sorted(list_of_strings[i]))
    list_of_strings.sort()
    return list_of_strings 

Edit: You don’t actually need to return list. The list you passed as parameter is “updated”. But if you call this function like sort_list(["aef","eghab"]), then you need to assign this function to another variable to retrieve sorted list

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement