w3resource

NumPy: Construct an array by repeating


Repeat Array Entirely

Write a NumPy program to construct an array by repeating.
Sample array: [1, 2, 3, 4]

Pictorial Presentation:

NumPy: Construct an array by repeating

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating an original array
a = [1, 2, 3, 4]
print("Original array")
print(a)

# Repeating the original array two times using np.tile
print("Repeating 2 times")
x = np.tile(a, 2)
print(x)

# Repeating the original array three times using np.tile
print("Repeating 3 times")
x = np.tile(a, 3)
print(x)

Sample Output:

Original array                                                         
[1, 2, 3, 4]                                                           
Repeating 2 times                                                      
[1 2 3 4 1 2 3 4]                                                      
Repeating 3 times                                                      
[1 2 3 4 1 2 3 4 1 2 3 4]

Explanation:

In the above code -

a = [1, 2, 3, 4]: A list a is defined with four elements.

x = np.tile(a, 2): np.tile repeats the given list a 2 times along its first axis. In this case, a is repeated twice, creating a new NumPy array: [1, 2, 3, 4, 1, 2, 3, 4].

x = np.tile(a, 3): np.tile repeats the given list a 3 times along its first axis. In this case, a is repeated thrice, creating a new NumPy array: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4].


For more Practice: Solve these Related Problems:

  • Repeat a one-dimensional array using np.tile and validate that its shape is doubled or tripled as expected.
  • Create a function to repeat an array and then reshape the repeated output into a matrix.
  • Verify that the sum of a repeated array equals the original array’s sum multiplied by the number of repetitions.
  • Repeat an array entirely and compare the result with manual concatenation of the original array.

Go to:


PREV : Test Any Element is True
NEXT : Repeat Each Array Element


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.