0

I currently have some Python code that samples a sine wave over a given number of steps:

import numpy as np

step = 2*pi / 20
time = np.arange(0,2*pi + step,step)
x_range = np.sin(time)
print(x_range)

I would now like to insert two separate characters,'m' and 'np' after each existing entry in x_range, such that the final list looks something like this:

[value1, m, np, value2, m, np, value3, m, np, value4 .....]

Does anyone know how this can be done?

Thanks in advance

tjsmert44
  • 121
  • 1
  • 12
  • Does this answer your question? [Insert an element at a specific index in a list and return the updated list](https://stackoverflow.com/questions/14895599/insert-an-element-at-a-specific-index-in-a-list-and-return-the-updated-list) – Woodford Jan 12 '22 at 16:47

3 Answers3

1

Make use of a comprehension to make it easy and succint.

new_list = []
{new_list.extend([e, 'm', 'np']) for e in x_range}
print(new_list)

This produces:

[value1, 'm', 'np', value2, 'm', 'np', value3, 'm', 'np', ...]
0

Something like that should do the work:

import numpy as np

step = 2*pi / 20
time = np.arange(0,2*pi + step,step)
x_range = np.sin(time)

new_list = list()

for i in x_range:
    new_list.append(i)
    new_list.append('m')
    new_list.append('np') 
print(new_list)

Just build a new list and add to it the value followed by the other two characters that you want and repeat the process for each value using for loop.

The output from the above code will be:

[0.0, 'm', 'np', 0.3090169943749474, 'm', 'np', 0.5877852522924731, 'm', 'np', 0.8090169943749475, 'm', 'np', 0.9510565162951535, 'm', 'np', 1.0, 'm', 'np', 0.9510565162951536, 'm', 'np', 0.8090169943749475, 'm', 'np', 0.5877852522924732, 'm', 'np', 0.3090169943749475, 'm', 'np', 1.2246467991473532e-16, 'm', 'np', -0.3090169943749473, 'm', 'np', -0.587785252292473, 'm', 'np', -0.8090169943749473, 'm', 'np', -0.9510565162951535, 'm', 'np', -1.0, 'm', 'np', -0.9510565162951536, 'm', 'np', -0.8090169943749476, 'm', 'np', -0.5877852522924734, 'm', 'np', -0.3090169943749477, 'm', 'np', -2.4492935982947064e-16, 'm', 'np']
Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18
0

It is also possible using list comprehension:

[item for sublist in [[ele, 'm', 'np'] for ele in x_range] for item in sublist]

Here you create a list with multiple lists [ele, 'm', 'np'] and you can unpack that list.

Or using list:

l = list(x_range)
for i in range(len(l), 0, -1):
    l.insert(i, 'np')
    l.insert(i, 'm')
3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18