How to Sort a List In Order of Element’s Length in Python


In this example we will show how to sort a list with rows based on the length of the element.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

b = input("Please input an element or '#' to quit: ")
if b == "#":
    print("Quit!")
else:
    a = []
    while b != "#":
        a.append(b)
        b = input("Please input an element or '#' to quit: ")
    a.sort(key=len)
    print("After sorting: ", a)

Output:

Please input an element or '#' to quit: Banana
Please input an element or '#' to quit: Pineapple
Please input an element or '#' to quit: Cat
Please input an element or '#' to quit: Apple
Please input an element or '#' to quit: #
After sorting: ['Cat', 'Apple', 'Banana', 'Pineapple']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments