Sort a List Without Modifying the Original in Python
To sort a list without modifying the original, you can use the sorted()
function in Python. This function returns a new sorted list while keeping the original list unchanged.
Examples
1. Using sorted()
to Sort a List Without Modifying the Original
The sorted()
function returns a new list that is sorted, leaving the original list unmodified.
# Original list
numbers = [5, 2, 9, 1, 5, 6]
# Sorting without modifying the original list
sorted_numbers = sorted(numbers)
# Printing both lists
print("Original List:", numbers)
print("Sorted List:", sorted_numbers)
In this example, we:
- Define an original list called
numbers
that contains unsorted values. - Use the
sorted()
function to create a new sorted list calledsorted_numbers
. - Print both lists to verify that the original list remains unchanged.
The sorted()
function does not alter the numbers
list; it simply returns a new list with sorted elements.
Output:
Original List: [5, 2, 9, 1, 5, 6]
Sorted List: [1, 2, 5, 5, 6, 9]
2. Sorting in Descending Order Without Modifying the Original
By passing the reverse=True
argument to sorted()
, we can sort the list in descending order.
# Original list
numbers = [3, 8, 1, 7, 4]
# Sorting in descending order without modifying the original list
sorted_descending = sorted(numbers, reverse=True)
# Printing both lists
print("Original List:", numbers)
print("Sorted List (Descending):", sorted_descending)
Here, we:
- Use the
sorted()
function with thereverse=True
parameter. - Create a new list
sorted_descending
that holds the sorted values in descending order. - Verify that the original list remains unchanged by printing it.
The reverse=True
argument ensures that the sorting is done in descending order.
Output:
Original List: [3, 8, 1, 7, 4]
Sorted List (Descending): [8, 7, 4, 3, 1]
3. Sorting a List of Strings Without Modifying the Original
We can use sorted()
to sort a list of strings alphabetically while keeping the original list unchanged.
# Original list of strings
words = ["banana", "apple", "cherry", "date"]
# Sorting alphabetically without modifying the original list
sorted_words = sorted(words)
# Printing both lists
print("Original List:", words)
print("Sorted List:", sorted_words)
In this example, we:
- Create an unsorted list of strings named
words
. - Use
sorted()
to create a new alphabetically sorted list calledsorted_words
. - Print both lists to confirm that the original remains unchanged.
Output:
Original List: ['banana', 'apple', 'cherry', 'date']
Sorted List: ['apple', 'banana', 'cherry', 'date']
Conclusion
To sort a list without modifying the original, the best approach is to use the sorted()
function. It:
- Returns a new sorted list while preserving the original.
- Allows sorting in ascending or descending order using the
reverse=True
parameter. - Works with numbers, strings, and other sortable data types.