🔄 Sorting Lists
Python provides multiple ways to sort lists, from simple ascending order to complex custom sorting. Understanding these methods is essential for data organization and manipulation.
# Basic list sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
🎯 Sorting Methods
Python offers two main approaches to sorting lists.
Basic Examples
# Different ways to sort lists
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# In-place sorting
numbers.sort()
print(f"Sorted in-place: {numbers}")
# Create new sorted list
original = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(original)
print(f"Original: {original}")
print(f"New sorted list: {sorted_numbers}")
# Descending order
numbers.sort(reverse=True)
print(f"Descending order: {numbers}")
🔍 Custom Sorting
Python allows custom sorting using the key
parameter.
# Custom sorting examples
# Sort by length
words = ["cat", "mouse", "elephant"]
words.sort(key=len)
print(f"Sorted by length: {words}")
# Sort by second element
pairs = [(1, 5), (2, 3), (3, 8)]
pairs.sort(key=lambda x: x[1])
print(f"Sorted by second element: {pairs}")
# Case-insensitive sorting
names = ["Alice", "bob", "Charlie"]
names.sort(key=str.lower)
print(f"Case-insensitive sort: {names}")
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.