python / beginner
Snippet
Sorting Lists without Changing the Original
The sorted() function creates a brand new list containing the elements of the original list in ascending order. The original list remains unchanged, which is safer for data integrity.
snippet.py
1
2
3
4
5
6
7
numbers = [42, 7, 13, 89, 1]# Create a new sorted listsorted_numbers = sorted(numbers)print(f"Original: {numbers}")print(f"Sorted: {sorted_numbers}")
Breakdown
1
sorted(numbers)
A built-in function that returns a new, sorted version of any iterable.
2
numbers
Notice that the original list 'numbers' still has its original unsorted order.