# Sort a list according to the Length of the Elements in Python program

We have a list of strings and our goal is to sort the list based on the length of strings in the list. We have to arrange the strings in ascending order according to their lengths. We can do this using our algorithms or Python built-in method sort() or function sorted() along with a key.

Let's take an example to see the output.

Input:
strings = ["hafeez", "aslan", "honey", "appi"]
Output:
["appi", "aslan", "honey", "hafeez"]

Let's write our program using sort(key) and sorted(key). Follow the below steps to achieve the desired output using a sorted(key) function.

## Algorithm

1. Initialize the list of strings.
2. Sort the list by passing list and key to the sorted(list, key = len) function. We have to pass len as key for the sorted() function as we are sorting the list based on the length of the string. Store the resultant list in a variable.
3. Print the sorted list.

## Example

Live Demo

## initializing the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]
## using sorted(key) function along with the key len
sorted_list = list(sorted(strings, key = len))
## printing the strings after sorting
print(sorted_list)

## Output

If you run the above program, you will get the following output.

['appi', 'aslan', 'honey', 'hafeez']


## Algorithm

1. Initialize the list of strings.
2. Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable.
3. Print the list.

## Example

Live Demo

## initializing the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]
## using sort(key) method to sort the list in place
strings.sort(key = len)
## printing the strings after sorting
print(strings)

## Output

If you run the above program, you will get the following output.

['appi', 'aslan', 'honey', 'hafeez']


## Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

Updated on: 23-Oct-2019

4K+ Views

##### Kickstart Your Career

Get certified by completing the course

Advertisements