Lecture
Sorting List Elements with the sort() Function
In Python, the sort() function sorts the elements of a list based on a specified criterion.
It modifies the original list in place, meaning it does not return a new list but instead changes the order of the existing one.
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, pass 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 provide a custom sorting rule using the key parameter. This allows you to define how elements are compared.
For example, to sort a list of strings by their length, you can pass key=len to the sort() function
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)
Previous lessonUsing the clear() Function to Remove All Values in a ListNext lessonHow to Check if a List Contains a Specific Element
Lessons in this chapter · List and Tuple data types for storing data in sequence
- 1. How to Store Ordered Data List
- 2. How to Utilize Values in a List
- 3. List IndexError Exception Handling
- 4. How to Concatenate, Repeat, and Determine the Length of Lists
- 5. Adding Elements with append() and insert()
- 6. Multiple-choice quiz
- 7. Comparing List Concatenation and Element Addition in Python
- 8. Removing Elements with the del Keyword and pop() Function
- 9. Removing an Element with a Specific Value using remove() Function
- 10. Using the clear() Function to Remove All Values in a List
- 11. Sorting List Elements with the sort() Function
- 12. How to Check if a List Contains a Specific Element
- 13. Multiple-choice quiz
- 14. Immutable Data Type, Tuple
- 15. Immutability of Tuples and Exception Handling
- 16. Accessing Specific Elements with Tuple Indexing
- 17. Selecting a Portion of a Tuple with Slicing
- 18. How to Perform Operations on Tuples
- 19. Coding Quiz - Sorting Lists
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
Quiz
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
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help