Reversing an array in Python refers to the process of changing the order of elements in an array so that the elements are arranged in reverse order. This means that the first element of the original array becomes the last element in the reversed array, the second element becomes the second-to-last element, and so on.
Methods to Reverse an Array in Python
There are several methods to reverse an array in Python. Some of the popular methods are:
- Reverse an Array in Python Using the reverse() method
- Reverse an Array in Python Using slicing
- Reverse an Array in Python Using the reversed() method
- Reverse an Array in Python Using recursion
- Reverse an Array in Python Using loop
Approach-1: Reverse an Array in Python Using the reverse() method
Let’s see how to reverse an array in python. The simplest and most straightforward method of reversing an array in Python is to use the reverse() method. The reverse() method is an in-built method in Python and can be applied to lists, arrays, and tuples.
Example code to reverse an array using the reverse() method
Code:
# Define an array
array = [1, 2, 3, 4, 5]
# Use the reverse() method to reverse the array
array.reverse()
# Print the reversed array
print("Reversed array: ", array)
Output:
Reversed array: [5, 4, 3, 2, 1]
Explanation:
- The first line of code defines an array called array with the values [1, 2, 3, 4, 5].
- In the second line, the reverse() method is used to reverse the array.
- Finally, the last line of code prints the reversed array using the print() function. The output of the code is Reversed array: [5, 4, 3, 2, 1], which shows that the order of elements in the array has been reversed.
Approach-2: Reverse an Array in Python Using slicing
Slicing is another simple method to reverse an array in Python. In this method, we slice the array in reverse order to get the reverse of the array.
Example code to reverse an array using slicing
# Define an array
array = [1, 2, 3, 4, 5]
# Use slicing to reverse the array
reversed_array = array[::-1]
# Print the reversed array
print("Reversed array: ", reversed_array)
Output:
Reversed array: [5, 4, 3, 2, 1]
Explanation:
- The first line of code defines an array called array with the values [1, 2, 3, 4, 5].
- In the second line, slicing is used to reverse the array. Slicing is a feature in Python that allows you to extract a portion of a list.
- The slicing syntax array[::-1] creates a new list with the array elements in reverse order. The :: symbol is used to specify the step of the slice and -1 means to step backward through the list.
- Finally, the last line of code prints the reversed array using the print() function. The output of the code is Reversed array: [5, 4, 3, 2, 1], which shows that the order of elements in the array has been reversed.
Approach-3: Reverse an Array in Python Using the reversed() method
The reversed() method is another in-built method in Python that can be used to reverse an array. The reversed() method returns a reverse iterator, which can be used to get the elements of the array in reverse order. Example code of how to reverse an array in python
Code:
# Example code to reverse an array using the reversed() method
# Define an array
array = [1, 2, 3, 4, 5]
# Use the reversed() method to reverse the array
reversed_array = list(reversed(array))
# Print the reversed array
print("Reversed array: ", reversed_array)
Output:
Reversed array: [5, 4, 3, 2, 1]
Explanation:
- The first line of code defines an array called array with the values [1, 2, 3, 4, 5].
- In the second line, the reversed() method is used to reverse the array. The reversed() method returns a reverse iterator, which is an object that produces the items of a list in reverse order.
- To use this method, the result must be converted to a list, which is done by passing the result to the list() function.
- Finally, the last line of code prints the reversed array using the print() function. The output of the code is Reversed array: [5, 4, 3, 2, 1], which shows that the order of elements in the array has been reversed.
Approach-4: How to print a list backward in python Using recursion
Recursion is a method where a function calls itself to reverse an array in Python. The recursive approach works by dividing the array into two parts, the first element and the rest of the array.
Code:
# Example code to reverse an array using recursion
def reverse_array(array, start, end):
if start < end:
array[start], array[end] = array[end], array[start]
reverse_array(array, start + 1, end - 1)
# Define an array
array = [1, 2, 3, 4, 5]
# Reverse the array using recursion
reverse_array(array, 0, len(array) - 1)
# Print the reversed array
print("Reversed array: ", array)
Output:
Reversed array: [5, 4, 3, 2, 1]
Explanation:
- The first section of the code defines a function called reverse_array that takes three arguments: array, start, and end.
- The function implements a recursive algorithm to reverse the elements of an array. The function starts with a check to see if the start index is less than the end index. If this condition is true, the function swaps the values at the start and end indices using tuple unpacking, then calls the reverse_array function again with the start index incremented by 1 and the end index decremented by 1. This process continues until the start index is equal to or greater than the end index.
- The second section of the code defines the array [1, 2, 3, 4, 5]. In the next line, the reverse_array function is called with the array, 0 (the starting index).
Approach-5: Reverse an Array in Python Using loop
The loop method involves iterating through the array from both ends and swapping the elements until the middle of the array is reached.
Code:
# Example code to reverse an array using a loop
def reverse_array(array):
start = 0
end = len(array) - 1
while start < end:
array[start], array[end] = array[end], array[start]
start += 1
end -= 1
# Define an array
array = [1, 2, 3, 4, 5]
# Reverse the array using a loop
reverse_array(array)
# Print the reversed array
print("Reversed array: ", array)
Output:
Reversed array: [5, 4, 3, 2, 1]
Explanation:
- The code defines a function reverse_array that reverses an array by swapping the elements at the start and end of the array and then repeating the process, moving the start and end indices one step closer to each other until they meet in the middle.
- The function takes in the array and the indices of the first and last elements of the array as inputs. The code then creates an array [1, 2, 3, 4, 5] and calls the reverse_array function, passing the array as an argument. This reverses the array in place, changing the order of its elements.
- Finally, the code prints the reversed array, which outputs Reversed array: [5, 4, 3, 2, 1].
Best Approach to Reverse an Array in Python
The best approach to reverse an array in Python depends on the size of the array and the requirements of the specific use case.
For small arrays, any of the methods discussed above can be used, such as slicing, the reversed() function, or the in-place reversal method.
However, for large arrays, the most efficient method is the in-place reversal method using a loop. This method has a time complexity of O(n), where n is the number of elements in the array, making it suitable for reversing large arrays.
Sample Problem on reversing array in Python:
Sample Problem 1
How to reverse the elements of an array using the slicing method.
Code:
def reverse_array_slicing(arr):
return arr[::-1]
arr = [1, 2, 3, 4, 5]
print("Original array: ", arr)
print("Reversed array: ", reverse_array_slicing(arr))
Output:
Original array: [1, 2, 3, 4, 5] Reversed array: [5, 4, 3, 2, 1]
Explanation:
- we define a function reverse_array_slicing that takes in an array arr as input.
- The function returns the reversed array using slicing. Slicing in Python is a way to extract a portion of an array, list, or any other sequence data type.
- The syntax for slicing is sequence[start:end:step]. In this case, we use a step of -1, which means to step backward through the array. This effectively reverses the array.
- The start and end indices are omitted, which means that the slicing will start from the first element and go until the last element of the array.
Sample Problem 2:
How to use the reversed() function to reverse the elements of a list.
Code:
# Define a function that takes a list as an argument
def reverse_list_reversed(arr):
# Use the reversed() function to reverse the elements of the list
return list(reversed(arr))
# Initialize a list
arr = [1, 2, 3, 4, 5]
# Print the original and reversed lists
print("Original list: ", arr)
print("Reversed list: ", reverse_list_reversed(arr))
Output:
Original array: [1, 2, 3, 4, 5] Reversed array: [5, 4, 3, 2, 1]
Explanation:
- The reverse_list_reversed function takes a list as an argument and returns the reversed version of that list.
- Inside the function, the reversed() function is used to reverse the elements of the list.
- The reversed() function returns an iterator, so we use the list() function to convert it to a list. The original list and the reversed list are printed to show the result.
Sample Problem 3
Write a python script to reverse a two-dimensional array in Python.
Code:
def reverse_2d_array(arr):
# loop through each sub-array
for i in range(len(arr)):
# reverse the current sub-array
arr[i] = arr[i][::-1]
# reverse the entire 2D array
return arr[::-1]
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original 2D array: ", arr)
print("Reversed 2D array: ", reverse_2d_array(arr))
Output:
Original 2D array: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Reversed 2D array: [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
Explanation:
- The function reverse_2d_array takes a 2D array arr as an input.
- The first for loop iterates through each sub-array of the 2D array.
- For each sub-array, it reverses the elements of the sub-array using slicing [::-1].
- After reversing all the sub-arrays, the function reverses the entire 2D array using slicing [::-1].
- The original 2D array and the reversed 2D array are printed to verify the result.
Sample Problem 4
How to reverse a string in Python using the reversed() function.
Code:
# define a function that takes a string as input
def reverse_string(string):
# convert the string into a list of characters
char_list = list(string)
# use the reversed() function to reverse the list of characters
reversed_char_list = list(reversed(char_list))
# join the reversed list of characters into a single string
reversed_string = "".join(reversed_char_list)
# return the reversed string
return reversed_string
# test the function with a sample string
string = "Hello World!"
print("Original string: ", string)
print("Reversed string: ", reverse_string(string))
Output:
Original string: Hello World!
Reversed string: !dlroW olleH
Explanation:
- we first define a string “Hello World”. Then, we use the reversed() function to reverse the elements of the string. The reversed() function returns an object of class reversed, which is an iterator that yields the elements of the input in reverse order.
- To get the reversed string as a single string, we use the join() method, which concatenates the elements of an iterable (in this case, the reversed() object) into a single string.
Finally, we print the reversed string using the print() function.
Sample Problem 5
Write a python script using a while loop to reverse the elements of an array in place.
Code:
def reverse_array_while(arr):
start = 0
end = len(arr) - 1
while start < end:
# swap elements at start and end
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
arr = [1, 2, 3, 4, 5]
print("Original array: ", arr)
print("Reversed array: ", reverse_array_while(arr)),
Output:
Original array: [1, 2, 3, 4, 5]
Reversed array: [5, 4, 3, 2, 1]
Explanation:
- we define a function reverse_array_while that takes an array as an input.
- We define two variables start and end which represent the start and end index of the array. the start is initialized to 0 and the end is initialized to the length of the array minus 1 (to account for 0-indexing).
- The while loop runs until the start is less than the end. Within the loop, we swap the elements at the index start and end using tuple unpacking.
- Then we increment the start by 1 and decrement the end by 1. After the loop, we return the reversed array. Finally, we test the function with an array [1, 2, 3, 4, 5] and print the original and reversed arrays.
Conclusion
Reversing an array refers to changing the order of its elements so that they are arranged in reverse order. There are multiple methods to reverse an array, including slicing, the reversed() function, and a loop. The best approach depends on the size of the array and the specific use case.
For example, if reversing a large array, the loop method is more efficient. If preserving the original array is important, slicing or the reversed() function is a better choice. It’s important to choose the right method based on the specific requirements and to consider memory constraints while reversing an array.
With these methods, reversing arrays, lists, tuples, and other sequence data types in Python is straightforward.