search

How to sort a list in Python?

You can sort a list in Python using the sort method of the list object. By default, the sort method sorts the elements of the list in ascending order.

For example:

# Sorting a list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers)  # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

# Sorting a list of strings
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.sort()
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']

You can also sort the list in descending order by passing the **reverse** argument to the **sort** method and setting it to **True**.

For example:

# Sorting a list of numbers in descending order
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort(reverse=True)
print(numbers)  # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

# Sorting a list of strings in descending order
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.sort(reverse=True)
print(fruits)  # Output: ['orange', 'cherry', 'banana', 'apple']

Note that the **sort** method modifies the original list and returns **None**. If you want to sort a list and get a new sorted list without modifying the original list, you can use the **sorted** function.

Related Questions You Might Be Interested