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

This is a Python Program to sort a list according to the length of the elements.

Problem Description

The program takes a list and sorts the list according to the length of the elements.

Problem Solution

1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list giving the length of the elements as the key.
4. Display the sorted list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to sort a list according to the length of the elements. The program output is also shown below.

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)
Program 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.

advertisement
Runtime Test Cases
 
Case 1:
Enter number of elements:4
Enter element:"Apple"
Enter element:"Ball"
Enter element:"Cat"
Enter element:"Dog"
['Cat', 'Dog', 'Ball', 'Apple']
 
Case 2:
Enter number of elements:4
Enter element:"White"
Enter element:"Red"
Enter element:"Purple"
Enter element:"Orange"
['Red', 'White', 'Purple', 'Orange']

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

👉 Apply Now for Free C Certification - January 2026

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations