 Open in App
Not now

# Repeat all the elements of a NumPy array of strings

• Last Updated : 05 Mar, 2023

Let us see how to repeat all elements of the given array of string 3 times. Example :

We will be using the numpy.char.multiply(a, i) method for this task.

## numpy.char.multiply(a, i)

Syntax : numpy.char.multiply(a, i) Parameters :

• a : array of str or unicode
• i : number of times to be repeated

Returns : Array of strings

Example 1 : Repeating 3 times.

## Python3

 `# importing the module` `import` `numpy as np`   `# created array of strings` `arr ``=` `np.array([``'Akash'``, ``'Rohit'``, ``'Ayush'``, ` `                ``'Dhruv'``, ``'Radhika'``], dtype ``=` `np.``str``)` `print``("Original Array :")` `print``(arr)`   `# with the help of np.char.multiply()` `# repeating the characters 3 times` `new_array ``=` `np.char.multiply(arr, ``3``)` `print``("\nNew array :")` `print``(new_array)`

Output :

Time complexity: O(n), where n is the length of the input array
Auxiliary space: O(n).

Example 2: Repeating 2 times.

## Python3

 `# importing the module` `import` `numpy as np`   `# created array of strings` `arr ``=` `np.array([``'Geeks'``, ``'for'``, ``'Geeks'``])` `print``("Original Array :")` `print``(arr)`   `# with the help of np.char.multiply()` `# repeating the characters 3 times` `new_array ``=` `np.char.multiply(arr, ``2``)` `print``("\nNew array :")` `print``(new_array)`

Output :

```Original Array :
['Geeks' 'for' 'Geeks']

New array :
['GeeksGeeks' 'forfor' 'GeeksGeeks']```

Time complexity: O(n), where n is the number of characters in the original array.

Auxiliary space: O(n), where n is the number of characters in the original array.

EXAMPLE 3 – Method 2: We can use a list comprehension to repeat each string in the array multiple times .

## Python3

 `# importing the module` `import` `numpy as np`   `# created array of strings` `arr ``=` `np.array([``'Geeks'``, ``'for'``, ``'Geeks'``])` `print``(``"Original Array :"``)` `print``(arr)`   `# using list comprehension to repeat each string in the array` `n ``=` `2`  `# number of times to repeat each string` `new_array ``=` `np.array([s ``*` `n ``for` `s ``in` `arr])` `print``(``"\nNew array :"``)` `print``(new_array)`

OUTPUT-

Original Array :
[‘Geeks’ ‘for’ ‘Geeks’]

New array :
[‘GeeksGeeks’ ‘forfor’ ‘GeeksGeeks’]

Time complexity: O(n * k), where n is the length of the input array and k is the number of times each string is repeated.
Auxiliary space: O(n), as we create a new list of length n to store the repeated strings. However, this is not counting the space needed for the input and output arrays.

My Personal Notes arrow_drop_up
Related Articles