NumPy tile()

The tile() method constructs an array by repeating arrays.

Example

import numpy as np

# create an array
array1 = np.array([0, 1, 2, 3, 4])

# create an array by repeating array1 3 times array2 = np.tile(array1, 3)
print(array2) # Output: [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]

tile() Syntax

The syntax of tile() is:

numpy.tile(array, repetitions)

tile() Arguments

The tile() method takes two arguments:

  • array - an array with elements to repeat
  • repetitions - number of times the array repeats

tile() Return Value

The tile() method returns a new array with repetition of the input array.


Example 1: Tile a 1-D Array

import numpy as np

# create an array
array1 = np.array([0, 1])

# tile array1 3 times array2 = np.tile(array1, 3) # tile array1 2 times in axis-0 and 3 times in axis-1 array3 = np.tile(array1, (2, 3))
print('1-D tile:\n', array2) print('2-D tile:\n', array3)

Output

1-D tile:
[0 1 0 1 0 1]
2-D tile:
 [[0 1 0 1 0 1]
 [0 1 0 1 0 1]]

In the following code segment

array3 = np.tile(array1,(2, 3))

the tuple (2, 3) indicates that array1 is repeated 2 times along axis 0 and 3 times along axis 1. This results in a 2-dimensional array with the repeated pattern.

Note: np.tile(array1, 0) removes all elements from an array.


Example 2: Tile a 2-D Array

We can tile a 2-D array similar to a 1-D array.

import numpy as np

# create an array
array1 = np.array(
    [[0, 1, 2], 
    [3, 4, 5]])

# tile twice array2 = np.tile(array1, 2) # tile twice on axis-0 and thrice on axis-1 array3 = np.tile(array1, (2,3)) # tile twice in each axis to make a 3-D array array4 = np.tile(array1, (2, 2, 2))
print('\nTile with 2 repetitions:\n',array2) print('\nTile with (2,3) repetitions:\n',array3) print('\nTile to make a 3-D array:\n',array4)

Output

Tile with 2 repetitions:
[[0 1 2 0 1 2]
 [3 4 5 3 4 5]]

Tile with (2,3) repetitions:
 [[0 1 2 0 1 2 0 1 2]
 [3 4 5 3 4 5 3 4 5]
 [0 1 2 0 1 2 0 1 2]
 [3 4 5 3 4 5 3 4 5]]

Tile to make a 3-D array:
 [[[0 1 2 0 1 2]
  [3 4 5 3 4 5]
  [0 1 2 0 1 2]
  [3 4 5 3 4 5]]

 [[0 1 2 0 1 2]
  [3 4 5 3 4 5]
  [0 1 2 0 1 2]
  [3 4 5 3 4 5]]]

Note: np.tile() is similar to np.repeat(), with the main difference being that tile() repeats arrays whereas repeat() repeats individual elements of the array.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges