How to sort a list?

QuestionsQuestions8 SkillsProYour First Python LabOct, 12 2025
087

You can sort a list in Python using the sort() method or the sorted() function. Here’s how to use both:

Using sort()

The sort() method sorts the list in place (modifies the original list).

my_list = [3, 1, 4, 1, 5]
my_list.sort()  # Sorts the list in ascending order
print(my_list)  # Output: [1, 1, 3, 4, 5]

Using sorted()

The sorted() function returns a new sorted list and does not modify the original list.

my_list = [3, 1, 4, 1, 5]
sorted_list = sorted(my_list)  # Returns a new sorted list
print(sorted_list)  # Output: [1, 1, 3, 4, 5]
print(my_list)      # Original list remains unchanged: [3, 1, 4, 1, 5]

Sorting in Descending Order

You can sort in descending order by passing the reverse=True argument.

my_list = [3, 1, 4, 1, 5]
my_list.sort(reverse=True)  # Sorts in place in descending order
print(my_list)  # Output: [5, 4, 3, 1, 1]

Feel free to ask if you have more questions about sorting or any other topic!

0 Comments

no data
Be the first to share your comment!