Author -  Sai gowtham

How to Sort an List by String Length in Python

In this tutorial, we will learn about how to sort an list of strings according to its string length in Python.

Consider, we have the following list of strings in Python:

aList = ["John", "Ram", "Joseph", "Peter"]

To sort the list by its string length, we can use the list.sort() method by passing key=len function as an argument.

Here is an example:

aList = ["John", "Ram", "Joseph", "Peter"]

aList.sort(key=len)
print(aList)

Output:

['Ram', 'John', 'Peter', 'Joseph']

In the code above, we have passed the key=len function as an argument to the sort() method. So, that it sorts the list based on the length of a string, by default the sort() method sorts the list in a ascending order.

If you want to sort a python list in a descending order, you can pass the reverse=True as a second argument to the sort() method.

Here is an example:

aList = ["John", "Ram", "Joseph", "Peter"]

aList.sort(key=len, reverse=True)
print(aList)

Output:

['Joseph', 'Peter', 'John', 'Ram']

Using the sorted() function

Similarly, we can also sort the python list by it’s string length using the sorted() function in python.

Here is an example:

aList = ["John", "Ram", "Joseph", "Peter"]

sortedList = sorted(aList, key=len)
print(sortedList)

Output:

['Ram', 'John', 'Peter', 'Joseph']

The sorted() takes the two arguments, the first argument is list we need to sort and the second argument is the sorting criteria function. So that it sorts the list based on the mentioned criteria.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY