---
jupyter:
  orphan: true
  jupytext:
    notebook_metadata_filter: all,-language_info
    split_at_heading: true
    text_representation:
      extension: .Rmd
      format_name: rmarkdown
      format_version: '1.2'
      jupytext_version: 1.14.1
  kernelspec:
    display_name: Python 3 (ipykernel)
    language: python
    name: python3
---

# Numpy repeat

Numpy has a very useful `repeat` function that has the effect of repeating elements to build up arrays.

```{python}
import numpy as np
```

In the simplest case, you can repeat a single element $n$ times.   For example, to make a new array that repeats the number 3 five times:

```{python}
np.repeat(3, 5)
```

Of course there are other ways to do that particular task, such as:

```{python}
np.zeros(5) + 3
```

However, `np.repeat` starts becoming more useful in slightly more complicated cases.  For example, to make an array that contains four repeats of the string `'yes'`:

```{python}
np.repeat('yes', 4)
```

`np.repeat` really starts coming into its own when you want to repeat more than one element.   For example, let us say that, for some reason, you wanted an array that repeated 3 five times followed by 2 five times.  In that case you send the two elements you want to be repeated as the first argument, and the number of repeats as the second:

```{python}
np.repeat([3, 2], 5)
```

You can also specify the number of repeats *for each element*.  For example, say you wanted 10 five times and 20 eight times:

```{python}
# 10 repeated 5 times followed by 20 repeated 8 times.
np.repeat([10, 20], [5, 8])
```

Or `'yes'` repeated four times followed by `'no'` repeated six times:

```{python}
# 'yes' repeated 4 times followed by 'no' repeated 6 times.
np.repeat(['yes', 'no'], [4, 6])
```

You can specify more than two elements, and give numbers of repeats to each element:

```{python}
# 'yes' repeated 2 times followed by 'no' repeated 3 times,
# followed by 'maybe' repeated 4 times.
np.repeat(['yes', 'no', 'maybe'], [2, 3, 4])
```
