understanding sort() vs sorted() in python
Feature sort()sorted()Works on Lists only Any iterable (lists, tuples, dictionaries, strings, etc.) Returns NoneNew sorted list Modifies original? Yes (in-place) No Usage list.sort()sorted(iterable)
sort() example
numbers = [4, 1, 3, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
sorted() example
numbers = [4, 1, 3, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4]
print(numbers) # Output: [4, 1, 3, 2] (unchanged)
With reverse and key arguments
key= → pass a function to sort by custom logic
words = ["banana", "apple", "cherry"]
# Sort by length
sorted_by_length = sorted(words, key=len)
print(sorted_by_length) # Output: ['apple', 'banana', 'cherry']
# Sort in reverse
words.sort(reverse=True)
print(words) # Output: ['cherry', 'banana', 'apple']
Python | ML | AI | Data Analytics
Let’s get started
LearnSkill - invest in yourself
