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
3
thislist = ["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
3
thislist = [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
3
thislist = ["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
3
thislist = [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

Frequently Asked Questions

To sort a list in Python, you can use the sort() method, which sorts the elements of the list in ascending order by default. You can also specify the sorting order by using the reverse parameter to sort in descending order.

The sort() method sorts the items of a list in-place, meaning it modifies the original list and does not return a new list. It sorts the elements in ascending order by default, but you can change this behavior by using the reverse=True argument.

No, the sort() method does not return a new list. It sorts the list in place, and the original list is modified. If you want to preserve the original list and create a sorted copy, you can use the sorted() function instead.

The choice between sort() and sorted() depends on your use case. If you need to sort a list in place and do not need a new sorted list, sort() is the preferred method. If you need to preserve the original list and return a sorted version, then sorted() is the better option since it creates a new list.

Still have questions?Contact our support team