Loading...
Sort List python
Sort List Python
In Python, lists are mutable data structures that can be easily sorted. The sort() method allows you to sort lists either alphanumerically or numerically. This lesson will cover how to sort lists in ascending and descending order.
1. Sort List Alphanumerically
The sort() method sorts the items of a list in place and returns None. By default, it sorts the list in ascending order. For strings, this means sorting them alphabetically.
Example: Sort Alphabetically
To sort a list of fruits alphabetically:
python
3 lines
|48/ 500 tokens
1 2 3thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() # Sorting the list alphabetically print(thislist) # Output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Code Tools
Example: Sort Numerically
To sort a list of numbers:
python
3 lines
|33/ 500 tokens
1 2 3thislist = [100, 50, 65, 82, 23] thislist.sort() # Sorting the list numerically print(thislist) # Output: [23, 50, 65, 82, 100]
Code Tools
2. Sort Descending
To sort a list in descending order, you can use the reverse keyword argument in the sort() method. Setting reverse = True will sort the list from highest to lowest.
Example: Sort Descending Alphabetically
To sort the list of fruits in descending order:
python
3 lines
|52/ 500 tokens
1 2 3thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort(reverse=True) # Sorting the list in descending order print(thislist) # Output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Code Tools
Example: Sort Descending Numerically
To sort the list of numbers in descending order:
python
3 lines
|38/ 500 tokens
1 2 3thislist = [100, 50, 65, 82, 23] thislist.sort(reverse=True) # Sorting the list in descending order print(thislist) # Output: [100, 82, 65, 50, 23]
Code Tools