Adding M0, M1, … Mn between each two elements in a list

I would like to loop through a list, which is called output as shown below:

output = [0, 1, 2, 3, 4, 5, 6]

But I have to exclude the first and last elements [1, 2, 3, 4, 5]

Then I would like to add between each two elements M. For the first two elements M0, the second two elements M1 and so on.

x= [1, M0, 2, M1, 3, M2, 4, M3, 5]

The expected output =

[[1, M0, 2],[2, M1, 3],[3, M2, 4],[4, M3, 5]]

And could I solve it with (while, for, and if) instead of using multiple for loops? Could you please assist me?

Below is my try:

Python code:

output = [0, 1, 2, 3, 4, 5, 6]

Total = []
for i in output:
    if i != output[0] and i != output[-1]:
        Total.append(i)
print(Total)
for j in (Total):
    print(j)

h = []
for x in Total:
    for y in (x,'M'0):
        h.append(y)
print(h)

Answer

Here is a solution you can try, using zip to create pairs & enumerate over that.

output = [0, 1, 2, 3, 4, 5, 6]

output = output[1:-1] # Remove first & last digit

print(
    [[i, f'M{index}', j] for index, (i, j) in enumerate(zip(output, output[1:]))]
)

[[1, 'M0', 2], [2, 'M1', 3], [3, 'M2', 4], [4, 'M3', 5]]

Leave a Reply

Your email address will not be published. Required fields are marked *