Guidelines

Sorting List Elements with the sort() Function

In Python, the sort() function sorts the elements of a list according to a specified criterion.

The sort() function sorts the list elements in place and does not create a new list.


How to Use the sort() Function

By default, the sort() function sorts the elements of a list in ascending order.

To sort in descending order, use sort(reverse=True).

Example of sort() Function
numbers = [3, 1, 4, 1, 5, 9, 2] # Ascending order numbers.sort() # [1, 1, 2, 3, 4, 5, 9] print("sorted:", numbers) # Descending order numbers.sort(reverse=True) # [9, 5, 4, 3, 2, 1, 1] print("reverse=True:", numbers)

Specifying a Sorting Criterion with the key Parameter

You can specify a sorting criterion using the key parameter.

For example, if you want to sort elements by the length of the strings, pass key=len to the sort() function as shown below.

Custom Sorting: Sort by String Length
words = ['banana', 'pie', 'Washington', 'apple'] # Sort by string length words.sort(key=len) # Output: ['pie', 'apple', 'banana', 'Washington'] print(words)
Mission
0 / 1

What is the most appropriate code to fill in the blank?

To specify a sorting criterion using the sort() function, use the parameter.
standard
len
key
put

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result