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:

JavaScript

So, this means I would expect:

JavaScript

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:

JavaScript

We can join that list to get sorted string:

JavaScript

So we can write this for the first part:

JavaScript

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

JavaScript

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