Flip the First K Elements of an Array – NumPy Python

In this article, We will see how to Flip the First K Elements of an Array in Python using NumPy. Numpy is a Python library that provides multidimensional, large arrays and matrices with mathematical functions to use with the arrays.

Requirements:

  • Numpy

You can install by using pip.

pip install numpy

Python Code to flip first k elements of a NumPy array:

In this code, I first created an array using the np.array()function with random values. If k is greater than the array length then it will return an error otherwise it will flip the first k element of the array with np.flip(array[:k]).

import numpy as np

# Initialize the array and the value of k
array = np.array([12, 21, 23, 34, 52])
k = 3

# Check if k is greater than the array length
if k > len(array):
    print("Error: k is larger than the array length.")
else:
    # Flip the first k elements
    array[:k] = np.flip(array[:k])

# Print the result
print(f"Flipped Array is: {array}")

Output:

Flipped Array is: [23 21 12 34 52]

Leave a Reply

Your email address will not be published. Required fields are marked *