# Find the first index of recurring elements

###### Posted By: Anonymous

Given a numpy array with recurring elements:

```
a = numpy.array([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1])
```

How can I find the first index of each recurring element (1, 2, 3, 1)? I would like it to return an array of indices:

```
>> index
array([0, 4, 7, 12])
```

Note: The elements in the array can repeat so they are not unique.

Edit: Is there a way that works for an array of strings as well?

```
a = numpy.array(["a", "a", "a", "a", "c", "c", "c", "b", "b", "b", "b", "b", "a", "a"])
```

## Solution

you can take a np.diff with np.where and add the 0th element:

```
np.concatenate(([0],np.where(np.diff(a)!=0)[0]+1))
```

```
array([ 0, 4, 7, 12], dtype=int64)
```

###### Answered By: Anonymous

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.