Python NumPy - Flip First K Elements of an Array

By IncludeHelp Last updated : March 8, 2024

Flipping k elements of an array refers to the process of reversing the order of k elements of the array.

For example, if we flip the first 3 elements of the array [1,2,3,4,5], the result would become [3,2,1].

Problem Statement

We are given a NumPy array and a variable k. We need to flip the first k values of the array.

Flipping First K Elements of an Array

To flip the first k elements of an array, we need to select the elements through indexing and then apply the np.flip() function. The np.flip() function either flips the entire array or the order of selected elements based on the parameter passed inside it. We can also pass the axis parameter. It defines the axis along which the flip operation must be performed.

Let us understand with the help of an example,

Example 1

# Importing numpy
import numpy as np

# Creating an array
arr = np.array([1, 2, 3, 4, 5])

# Display original array
print("Original array", arr, "\n")

# Defining a value for k
k = 3

# Select first k elements of array
arr = arr[:k]

# Flip the array elements
res = np.flip(arr)

# Display result
print("Result:\n", res, "\n")

Output

The output of the above program is:

Original array [1 2 3 4 5] 

Result:
 [3 2 1] 

Example 2

# Importing numpy
import numpy as np

# Creating an array
arr = np.array([3, 6, 4, 7, 4])

# Display original array
print("Original array", arr, "\n")

# Defining a value for k
k = 3

# Flip the array elements
res = np.flip(arr[:k])

# Display result
print("Result:\n", res, "\n")

Output

The output of the above program is:

Original array [3 6 4 7 4] 

Result:
 [4 6 3] 

To understand the above programs, you should have the basic knowledge of the following Python topics:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.