PYTHON
Reverse a List In-Place or Create a New Reversed List
Understand Python's list reversal methods: `list.reverse()` for in-place modification and `reversed()` for generating a new reversed iterator without altering the original list.
# Method 1: Reversing a list in-place using list.reverse()
my_list_inplace = [10, 20, 30, 40, 50]
print(f"Original list (in-place): {my_list_inplace}")
my_list_inplace.reverse()
print(f"Reversed list (in-place): {my_list_inplace}
")
# Method 2: Creating a new reversed list using reversed() and list()
my_list_new = ['a', 'b', 'c', 'd', 'e']
print(f"Original list (new): {my_list_new}")
reversed_iterator = reversed(my_list_new)
new_reversed_list = list(reversed_iterator)
print(f"New reversed list: {new_reversed_list}")
print(f"Original list (after new reversal): {my_list_new}
")
# Method 3: Creating a new reversed list using slicing
my_list_slice = ['x', 'y', 'z']
print(f"Original list (slicing): {my_list_slice}")
reversed_list_slice = my_list_slice[::-1]
print(f"Reversed list (slicing): {reversed_list_slice}")
How it works: This snippet illustrates three common ways to reverse lists in Python. `list.reverse()` modifies the list directly (in-place) and returns `None`, making it efficient for large lists when you no longer need the original order. The `reversed()` built-in function returns an iterator that yields elements in reverse order without modifying the original list; this iterator can then be converted to a list using `list()`. Finally, list slicing with `[::-1]` creates a new reversed shallow copy of the list, which is often the most concise and Pythonic way to get a reversed copy.