Flipping array is very useful while doing data analysis. Using it you can easily analyze time series data and examine trends. There are also many use cases when you have to flip an array. In this tutorial, you will learn how to flip an array in Python using various methods.
In this section,, you will know all the methods to flip an array in Python.
The first method you can use to flip an array in Python is the use of the reverse() function. Here you will use the dot operator with the input array.
Run the below lines of code to reverse the array.
array = [10, 20, 30, 40, 50]
array.reverse()
print(array)
Output
[50, 40, 30, 20, 10]
The other method to reverse the array is the use of the reversed() function with the list() function. Here you will first use the reversed() function on the array and then convert it to the list using the list() method.
Use the below lines of code to reverse the array.
array = [10, 20, 30, 40, 50]
reversed_array = list(reversed(array))
print(reversed_array )
Output
[50, 40, 30, 20, 10]
The other method to flip the array is to use the slicing technique. Here here you will use the square bracket with two colons and -1 inside it like [: : -1].
Execute the below lines of code to flip the array.
array = [10, 20, 30, 40, 50]
reversed_array = array[::-1]
print(array)
Output
[50, 40, 30, 20, 10]
You can also use the for-loop method to swap the elements one by one and flip the array.
Use the below lines of code.
array = [10, 20, 30, 40, 50]
n = len(array)
for i in range(n // 2):
array[i], array[n - i - 1] = array[n - i - 1], array[i]
print(array)
Output
[50, 40, 30, 20, 10]
That’s all for now. These are the methods to flip an array in Python. You can use any method on your needs and preferences. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.