×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

How to repeat each element of a NumPy array 5 times?

Learn, how to repeat each element of a NumPy array 5 times?
By Pranit Sharma Last updated : December 26, 2023

Problem statement

Suppose that we are given a numpy array and we need to repeat each of its elements 5 times with the array itself.

For example, if we have an array as [1,2,3,4], we need the output as [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4].

Repeating each element of a NumPy array 5 times

To repeat each element of a numpy array 5 times, we can use the numpy.repeat() function which is used to repeat the elements of an array N number of times, where N is the parameter, it accepts.

We can also repeat the whole array N number of times. For that purpose, we can use the numpy tile() function.

Let us understand with the help of an example,

Python code to repeat each element of a NumPy array 5 times

# Import numpy
import numpy as np

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

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

# Repeating each element 5 times
res = np.repeat(arr,5)

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

Output

Example: How to repeat each element of a NumPy array 5 times?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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