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

This Python program sorts a list of elements based on their lengths in ascending order. It demonstrates how to use the sorted() function with a custom sorting key to achieve this.

Problem Statement

Given a list of strings, you need to sort the list in ascending order based on the length of the strings.

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

def sort_by_length(input_list):
    sorted_list = sorted(input_list, key=len)
    return sorted_list

# Input
input_list = ["apple", "banana", "kiwi", "grapes", "orange", "strawberry"]

# Sorting by length
sorted_result = sort_by_length(input_list)

# Output
print("Original List:", input_list)
print("Sorted List by Length:", sorted_result)

How It Works

  1. Define a function sort_by_length(input_list) that takes a list of strings as input.
  2. Inside the function, use the sorted() function to sort the input list based on the len function as the sorting key. This means that the elements will be sorted based on their lengths.
  3. Return the sorted list.
  4. Outside the function, create an example input list of strings.
  5. Call the sort_by_length() function with the input list and store the sorted result.
  6. Print both the original input list and the sorted list based on length.

Input/Output

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...