How to Flip an Array in Python : 4 Methods

How to Flip an Array in Python

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.

Methods to flip an array in Python

In this section,, you will know all the methods to flip an array in Python.

Method 1: Using the reverse() function

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]

Method 2: Use the reversed() with the list() function

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]

Method 3: Using the slicing technique

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]

Method 4: Use loop

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]

Conclusion

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.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner