Reverse an Array
Understanding Array Reversal
Reversing an array involves changing the order of elements so that the first element becomes the last and vice versa.
We will explore three different methods to reverse an array using Python.
Method 1: Using Slicing
This method uses Python's slicing feature to reverse the array.
def reverse_array(arr): return arr[::-1] arr = [1, 2, 3, 4, 5] print(reverse_array(arr))
Method 2: Using Recursion
This method reverses the array using a recursive function.
def reverse_recursive(arr, start, end): if start >= end: return arr[start], arr[end] = arr[end], arr[start] reverse_recursive(arr, start + 1, end - 1) arr = [1, 2, 3, 4, 5] reverse_recursive(arr, 0, len(arr) - 1) print(arr)
Method 3: Using a Second List
This method stores the reversed elements in a new list.
def reverse_new_list(arr): rev_arr = [] for i in range(len(arr) - 1, -1, -1): rev_arr.append(arr[i]) return rev_arr arr = [1, 2, 3, 4, 5] print(reverse_new_list(arr))