ColeS - 1 year ago 43

Python Question

I am fairly new to Python and am confused how to represent the following code from Matlab into Python:

`P = [2:35,50,100,200]`

In Matlab, this will spit out: P = [2,3,...,35,50,100,200] ; however, I can't seem to figure out how to easily add values to an a list with sequential numbering as is easily done in Matlab. Any suggestions would be great. Thanks!

Answer Source

Vanilla python doesn't have a dedicated syntax for this ... If you're working with lists, you need 2 steps:

```
lst = list(range(2, 36))
lst.extend([50, 100, 200])
```

If you have the "bleeding edge" (python3.5), you *can* use unpacking:

```
lst = [*range(2, 36), 50, 100, 200]
```

If you're using `numpy`

, you can use the `r_`

index trick (which looks somewhat similar to the matlab version):

```
>>> import numpy as np
>>> np.r_[2:36, 100, 200, 500]
array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 100, 200, 500])
```