Wednesday, 22 September 2021

Python: Sort list of strings by length

By supplying a custom function to the ‘key’ argument to the sort, sorted function, we can sort the data on multiple attributes.

 

Find the below examples.

 

Example 1: Using sort method.

countries1.sort(key=len)

 

Example 2: Using sorted method.

countryies2_by_length = sorted(countries2, key=len)

Find the below working application.

 

sort_list_of_strings_by_length.py

def print_list(my_list, msg):
    print(msg)
    for item in my_list:
        print(item)
    print()

countries1 = ['Albania', 'Canada', 'Australia', 'India', 'Chile', 'Bhutan']
countries2 = ['Albania', 'Canada', 'Australia', 'India', 'Chile', 'Bhutan']

countries1.sort(key=len)

countryies2_by_length = sorted(countries2, key=len)

print_list(countries1, "Sorted by length using sort method")
print_list(countryies2_by_length, "Sorted by length using sorted function")


Output

Sorted by length using sort method
India
Chile
Canada
Bhutan
Albania
Australia

Sorted by length using sorted function
India
Chile
Canada
Bhutan
Albania
Australia

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment