Free Online Code Editor
Sort lists and custom objects.
# Basic sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_nums = sorted(numbers)
print(f"Sorted: {sorted_nums}")
print(f"Original: {numbers}") # Unchanged
# Sort in place
numbers.sort()
print(f"\nIn place: {numbers}")
# Reverse sort
print(f"\nReverse: {sorted(numbers, reverse=True)}")
# Sort strings
words = ["banana", "apple", "cherry", "date"]
print(f"\nWords: {sorted(words)}")
# Custom key function
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
by_grade = sorted(students, key=lambda s: s[1])
print(f"\nBy grade: {by_grade}")
# Sort by string length
words = ["python", "java", "c", "javascript"]
by_length = sorted(words, key=len)
print(f"\nBy length: {by_length}")
# Sort dictionary by value
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(f"\nScores (high to low): {sorted_scores}")sorted() returns new sorted list. sort() sorts in place. Use key parameter for custom sorting. reverse=True for descending.