by BehindJava
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
- User must enter the number of elements for the first list and store it in a variable.
- User must then enter the elements of the list one by one using a for loop and store it in a list.
- Then the list is sorted using the length of the elements as the key.
- The sorted list is then printed.