[Python] How to Use the sort() Function in Python with Examples
Hello, this is BlockDMask.
Today, we’ll take a deep look at how to use the sort()
method in Python to sort a list.
We’ll cover ascending and descending sorting, and clarify the difference between sort()
and sorted()
.
<Table of Contents>
- How the sort() method works in Python
- Ascending and descending sort with reverse parameter
- Difference between sort() and sorted()
1. How the sort() method works in Python
1-1) Basic usage of sort()
The list.sort()
method directly modifies the original list in place.
It does not return a new list. This method is only available for list objects.
Note: If you want to sort something without changing the original list, use sorted()
instead. We'll cover that later.
1-2) sort() examples with numbers and strings
# Sorting numbers
temperatures = [86, 74, 90, 61, 79, 68]
print("1. Sorted temperatures:")
temperatures.sort()
print(temperatures)
# Sorting strings (lowercase only)
cities = ['chicago', 'new york', 'atlanta', 'dallas']
print("\n2. Sorted cities:")
cities.sort()
print(cities)
# Sorting strings with mixed case
brands = ['Apple', 'samsung', 'Google', 'amazon']
print("\n3. Sorted brand names:")
brands.sort()
print(brands)
Explanation:
- 1. Temperature list:
[61, 68, 74, 79, 86, 90]
— sorted in increasing order. - 2. City names: Alphabetical sort:
['atlanta', 'chicago', 'dallas', 'new york']
. - 3. Brand names: Capital letters come first due to ASCII values. So
Apple
andGoogle
appear beforeamazon
andsamsung
.
ASCII (American Standard Code for Information Interchange) is a character encoding system where each letter, number, or symbol is represented by a numeric value.
For example:
• Capital letters:
'A' = 65
, 'B' = 66
, ..., 'Z' = 90
• Lowercase letters:
'a' = 97
, 'b' = 98
, ..., 'z' = 122
This is why capital letters come before lowercase letters when sorted — they have smaller ASCII values.
1-3) Extra Example: Sorting a list of names by last name
names = ['Elon Musk', 'Ada Lovelace', 'Alan Turing', 'Grace Hopper']
names.sort(key=lambda x: x.split()[-1])
print("\n4. Names sorted by last name:")
print(names)
Explanation: We're using key
to sort by the last word in each name (i.e., the last name).
This is useful for directories or contact apps.
2. Ascending and Descending Sort with reverse Parameter
The sort()
method has an optional reverse
parameter.
reverse=False
: sorts in ascending order (default)reverse=True
: sorts in descending order
prices = [299, 199, 499, 399, 599]
# Ascending order
prices_asc = prices.copy()
prices_asc.sort()
print("Ascending prices:")
print(prices_asc)
# Descending order
prices_desc = prices.copy()
prices_desc.sort(reverse=True)
print("\nDescending prices:")
print(prices_desc)
Explanation:
sort()
by default returns[199, 299, 399, 499, 599]
reverse=True
gives[599, 499, 399, 299, 199]
It's a good idea to use .copy()
if you want to keep the original list unchanged.
3. What’s the Difference Between sort() and sorted()?
Although they look similar, sort()
and sorted()
work differently under the hood:
Feature | sort() | sorted() |
---|---|---|
Returns | None | New sorted list |
Modifies original list? | ✅ Yes | ❌ No |
Available for | Lists only | Any iterable (list, tuple, string...) |
Example: Comparing sort() and sorted()
languages = ['Python', 'Java', 'C++', 'Go']
# Using sort()
result1 = languages.sort()
print("result1:", result1) # None
print("languages after sort():", languages)
# Using sorted()
languages2 = ['Python', 'Java', 'C++', 'Go']
result2 = sorted(languages2)
print("\nresult2:", result2)
print("languages2 after sorted():", languages2)
Output:
result1: None
languages after sort(): ['C++', 'Go', 'Java', 'Python']
result2: ['C++', 'Go', 'Java', 'Python']
languages2 after sorted(): ['Python', 'Java', 'C++', 'Go']
Takeaway:
sort()
is destructive: it changes your original list.sorted()
is safe: your original list stays the same.- If you're dealing with data that shouldn't be changed, always use
sorted()
.
That wraps up this tutorial on the sort()
method in Python and how it compares to sorted()
.
Thanks for reading, and happy coding!
Comments
Post a Comment