Python Sorting: sorted() vs .sort() with Examples

Python Sorting Explained: sorted() vs .sort() — With Examples Sorting data is a day-to-day task for any Python developer. But choosing between sorted() and .sort() can make a big difference depending on your use case. Let’s understand it with different datasets 👇 🔹 sorted() – Built-in Function ✅ Returns a new sorted list ✅ Original data remains unchanged ✅ Works with any iterable (list, tuple, set, dict keys) ❌ Uses extra memory (creates a copy) Example (Tuple of prices): prices = (450, 120, 890, 300) sorted_prices = sorted(prices) print(sorted_prices) # [120, 300, 450, 890] print(prices) # Original tuple remains unchanged 🔹 .sort() – List Method ✅ Sorts the list in-place ✅ Faster & memory-efficient ❌ Works only on lists ❌ Returns None Example (List of employee ages): ages = [32, 25, 45, 29] ages.sort() print(ages) # [25, 29, 32, 45] 🔹 Sorting with key Example (Sort students by marks): students = [ ("Ammar", 85), ("Ali", 92), ("Zara", 78) ] students.sort(key=lambda x: x[1]) print(students Reverse Sorting Example (Descending order): scores = [88, 67, 92, 74] print(sorted(scores, reverse=True)) # [92, 88, 74, 67 Quick Rule to Remember Use sorted() when you need to keep original data Use .sort() when performance matters and modification is okay Small choices in Python can make a big impact on performance and readability. #Python #DataStructures #LearningPython #CodingTips #Programming #DataAnalysis

To view or add a comment, sign in

Explore content categories