by BehindJava

Write a program to Sort a List According to the Length of the Elements in Python

Home » python » Write a program to Sort a List According to the Length of the Elements in Python

In this tutorial we are going to learn about Sorting a List According to the Length of the Elements in Python.

Python Program to Sort a List According to the Length of the Elements

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=input("Enter element:")
    a.append(b)
a.sort(key=len)
print(a)

Explanation

  1. User must enter the number of elements for the first list and store it in a variable.
  2. User must then enter the elements of the list one by one using a for loop and store it in a list.
  3. Then the list is sorted using the length of the elements as the key.
  4. The sorted list is then printed.