MWZ

MINDWAREZONE

Sorting Lists in Python

Sorting is a common operation when working with lists in Python. You can arrange list items in ascending or descending order using the built-in sort() method and the sorted() function.

In this tutorial, you'll learn how to sort lists in different ways with practical examples.

Using sort()

The sort() method sorts the original list in place, meaning it modifies the list directly.

Syntax

list_name.sort()
            

Example

numbers = [50, 10, 30, 20, 40] 
numbers.sort() 
print(numbers)
            

Output:

[10, 20, 30, 40, 50]
            

The list is sorted in ascending order by default.

Using sorted()

The sorted() function returns a new sorted list without changing the original list.

Syntax

sorted(iterable)
            

Example

numbers = [50, 10, 30, 20, 40] 
sorted_numbers = sorted(numbers) 
print(sorted_numbers) 
print(numbers)
            

Output:

[10, 20, 30, 40, 50] 
[50, 10, 30, 20, 40]
            

The original list remains unchanged.

Sorting in Ascending Order

Ascending order means arranging values from smallest to largest or alphabetically from A to Z.

Example: Numbers

numbers = [5, 2, 8, 1, 9] 
numbers.sort() 
print(numbers)
            

Output:

[1, 2, 5, 8, 9]
            

Example: Strings

fruits = ["Mango", "Apple", "Banana", "Orange"] 
fruits.sort() 
print(fruits)
            

Output:

['Apple', 'Banana', 'Mango', 'Orange']
            

Sorting in Descending Order

To sort a list in descending order, use the reverse=True argument.

Example: Using sort()

numbers = [5, 2, 8, 1, 9] 
numbers.sort(reverse=True) 
print(numbers)
            

Output:

[9, 8, 5, 2, 1]
            

Example: Using sorted()

numbers = [5, 2, 8, 1, 9] 
sorted_numbers = sorted(numbers, reverse=True) 
print(sorted_numbers)
            

Output:

[9, 8, 5, 2, 1]
            

Difference Between sort() and sorted()

Feature sort() sorted()
Modifies original list Yes No
Returns a new list No Yes
Works only on lists Yes No
Works on any iterable No Yes

Summary

Method Description
sort() Sorts the original list
sorted() Returns a new sorted list
reverse=True Sorts in descending order
key=str.lower Performs case-insensitive sorting