In Python, you can sort a list using the built-in sorted()
function. This function takes the list as an argument and returns a new list with the elements sorted in ascending order by default.
Here is an example of how to use the sorted()
function to sort a list of numbers:
# Define a list of numbers
numbers = [5, 2, 8, 1, 3]
# Sort the list in ascending order
sorted_numbers = sorted(numbers)
# Print the sorted list
print(sorted_numbers) # [1, 2, 3, 5, 8]
By default, the sorted()
function sorts the list in ascending order. If you want to sort the list in descending order, you can use the reverse
argument. This argument should be set to True
to sort the list in descending order.
Here is an example of how to use the sorted()
function with the reverse
argument to sort a list in descending order:
# Define a list of numbers
numbers = [5, 2, 8, 1, 3]
# Sort the list in descending order
sorted_numbers = sorted(numbers, reverse=True)
# Print the sorted list
print(sorted_numbers) # [8, 5, 3, 2, 1]
You can also use the sorted()
function to sort a list of strings. By default, the sorted()
function sorts the list in ascending order based on the ASCII values of the characters in the strings.
Here is an example of how to use the sorted()
function to sort a list of strings:
# Define a list of strings words = ["apple", "banana", "carrot", "dog"] # Sort the list in ascending order sorted_words = sorted(words) # Print the sorted list print(sorted_words) # ["apple", "banana", "carrot", "dog"]
You can use the optional key
argument in the sorted()
function to specify a function that transforms the items in the list before they are compared. This allows you to sort the list based on a specific criterion, such as the length of the strings in the list.
Here is an example of how to use the key
argument to sort a list of strings based on their length:
# Define a list of strings
words = ["banana", "apple", "carrot", "dog"]
# Sort the list based on the length of the strings
sorted_words = sorted(words, key=len)
# Print the sorted list
print(sorted_words) # ["dog", "apple", "banana", "carrot"]
In this example, the key
the function takes a string as an input and returns its length. This causes the sorted()
function to sort the list based on the length of the strings instead of their ASCII values.