Python list sort by length descending

Python | Sort a List according to the Length of the Elements

In this program, we need to accept a list and sort it based on the length of the elements present within.
Examples:

Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "ankita", "rinku"]] Output : [['gaurav'], ['ram', 'mohan', 'aman'], ['amy', 'sima', 'ankita', 'rinku']] Note: The first example comprises of Strings whose length can be calculated. The second example comprises of sublists, which is also arranged according to there length.

Sort a list according to the Length of the Elements in Python program

PythonServer Side ProgrammingProgramming



We have a list of strings and our goal is to sort the list based on the length of strings in the list. We have to arrange the strings in ascending order according to their lengths. We can do this using our algorithms or Python built-in method sort() or function sorted() along with a key.

Let's take an example to see the output.

Input: strings = ["hafeez", "aslan", "honey", "appi"] Output: ["appi", "aslan", "honey", "hafeez"]

Let's write our program using sort(key) and sorted(key). Follow the below steps to achieve the desired output using a sorted(key) function.

Python List sort() - Sorts Ascending or Descending List

The list.sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items.

Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.

Syntax:

list.sort(key=None, reverse=False)

Parameters:

  1. key: (Optional) A function that extracts a comparison key from each list element while sorting.
  2. reverse: (Optional) If true, the sorted list will be reversed. By default, it is False.

Return Value:

No return value. It sorts the list itself.

The following example demonstrates the sort() function on numeric lists.

Example: Sort Numeric List

Copy

nums = [1, 5, 3, 4, 2, 10, 6, 8, 7, 9] nums.sort() print('List in Ascending Order: ', nums) nums.sort(reverse=True) print('List in Descending Order: ', nums)

Output

List in Ascending Order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] List in Descending Order: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

The sort() method can also be used on character lists.

Example: Sort Char List

Copy

al = ['a','d','e','c','b'] al.sort(reverse=True) print('List in Descending Order: ', al) al.sort() print('List in Ascending Order: ', al)

Output

List in Descending Order: ['e', 'd', 'c', 'b', 'a'] List in Ascending Order: ['a', 'b', 'c', 'd', 'e']

The following example sorts the string list in alphabetical order.

Example: Sort String List

Copy

cities = ['Mumbai', 'London', 'Paris', 'New York'] cities.sort() print('List in Ascending Order: ', cities) cities.sort(reverse=True) print('List in Descending Order: ', cities)

Output

List in Ascending Order: ['London', 'Mumbai', 'New York', 'Paris'] List in Descending Order: ['Paris', 'New York', 'Mumbai', 'London']

Tuples

A tuple is a fixed size grouping of elements, such as an (x, y) co-ordinate. Tuples are like lists, except they are immutable and do not change size (tuples are not strictly immutable since one of the contained elements could be mutable). Tuples play a sort of "struct" role in Python -- a convenient way to pass around a little logical, fixed size bundle of values. A function that needs to return multiple values can just return a tuple of the values. For example, if I wanted to have a list of 3-d coordinates, the natural python representation would be a list of tuples, where each tuple is size 3 holding one (x, y, z) group.

To create a tuple, just list the values within parenthesis separated by commas. The "empty" tuple is just an empty pair of parenthesis. Accessing the elements in a tuple is just like a list -- len(), [ ], for, in, etc. all work the same.

tuple = (1, 2, 'hi') print len(tuple) ## 3 print tuple[2] ## hi tuple[2] = 'bye' ## NO, tuples cannot be changed tuple = (1, 2, 'bye') ## this works

To create a size-1 tuple, the lone element must be followed by a comma.

tuple = ('hi',) ## size-1 tuple

It's a funny case in the syntax, but the comma is necessary to distinguish the tuple from the ordinary case of putting an expression in parentheses. In some cases you can omit the parenthesis and Python will see from the commas that you intend a tuple.

Assigning a tuple to an identically sized tuple of variable names assigns all the corresponding values. If the tuples are not the same size, it throws an error. This feature works for lists too.

(x, y, z) = (42, 13, "hike") print z ## hike (err_string, err_code) = Foo() ## Foo() returns a length-2 tuple

List Comprehensions (optional)

List comprehensions are a more advanced feature which is nice for some cases but is not needed for the exercises and is not something you need to learn at first (i.e. you can skip this section). A list comprehension is a compact way to write an expression that expands to a whole list. Suppose we have a list nums [1, 2, 3, 4], here is the list comprehension to compute a list of their squares [1, 4, 9, 16]:

nums = [1, 2, 3, 4] squares = [ n * n for n in nums ] ## [1, 4, 9, 16]

The syntax is [ expr for var in list ] -- the for var in list looks like a regular for-loop, but without the colon (:). The expr to its left is evaluated once for each element to give the values for the new list. Here is an example with strings, where each string is changed to upper case with '!!!' appended:

strs = ['hello', 'and', 'goodbye'] shouting = [ s.upper() + '!!!' for s in strs ] ## ['HELLO!!!', 'AND!!!', 'GOODBYE!!!']

You can add an if test to the right of the for-loop to narrow the result. The if test is evaluated for each element, including only the elements where the test is true.

## Select values <= 2 nums = [2, 8, 1, 6] small = [ n for n in nums if n <= 2 ] ## [2, 1] ## Select fruits containing 'a', change to upper case fruits = ['apple', 'cherry', 'banana', 'lemon'] afruits = [ s.upper() for s in fruits if 'a' in s ] ## ['APPLE', 'BANANA']

Exercise: list1.py

To practice the material in this section, try later problems in list1.py that use sorting and tuples (in the Basic Exercises).

7. write a python program to sort a list according to the length of the elements

1 week ago

What is the sort() method in Python?

This method takes a list and sorts it in place. This method does not have a return value.

In this example, we have a list of numbers and we can use the sort() method to sort the list in ascending order.

my_list = [67, 2, 999, 1, 15] # this prints the unordered list print("Unordered list: ", my_list) # sorts the list in place my_list.sort() # this prints the ordered list print("Ordered list: ", my_list)

If the list is already sorted then it will return None in the console.

my_list = [6, 7, 8, 9, 10] # this will return None because the list is already sorted print(my_list.sort())

The sort() method can take in two optional arguments called key and reverse.

key has the value of a function that will be called on each item in the list.

In this example, we can use the len() function as the value for the key argument. key=len will tell the computer to sort the list of names by length from smallest to largest.

names = ["Jessica", "Ben", "Carl", "Jackie", "Wendy"] print("Unsorted: ", names) names.sort(key=len) print("Sorted: ", names)

reverse has a boolean value of True or False.

In this example, reverse=True will tell the computer to sort the list in reverse alphabetical order.

names = ["Jessica", "Ben", "Carl", "Jackie", "Wendy"] print("Unsorted: ", names) names.sort(reverse=True) print("Sorted: ", names)