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
1thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
2thislist.sort() # Sorting the list alphabetically
3print(thislist) # Output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Example: Sort Numerically
To sort a list of numbers:
python
1thislist = [100, 50, 65, 82, 23]
2thislist.sort() # Sorting the list numerically
3print(thislist) # Output: [23, 50, 65, 82, 100]
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
1thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
2thislist.sort(reverse=True) # Sorting the list in descending order
3print(thislist) # Output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Example: Sort Descending Numerically
To sort the list of numbers in descending order:
python
1thislist = [100, 50, 65, 82, 23]
2thislist.sort(reverse=True) # Sorting the list in descending order
3print(thislist) # Output: [100, 82, 65, 50, 23]