Search code examples
pythonlistinsertion

How to insert an element after every other element in python list


Hello I would like to know how to use a for loop to go through a list and insert an element after each other element in a new list.

I have looked at this link Insert element in Python list after every nth element

but when I tried that method it was giving me the exact same problem when implementing it in my code

"""
Created on Sat Mar 28 20:40:37 2020

@author: DeAngelo
"""

import math 
import matplotlib.pyplot as plt
import numpy as np
from numpy import sqrt
from quadpy import quad
import scipy.integrate as integrate
import scipy.special as special

experiment = [1,2,3,4,5]
count = len(experiment)

after = []
new = []
for i in range(0,count-1):
    average2 = (experiment[i] + experiment[i+1])/2
    new.append(average2)

print(experiment)

for i in range(0,count-1):
      just = experiment.insert(i+1,new[i])

print(new,'\n')      
print(experiment)

1st print(experiment) -> [1, 2, 3, 4, 5]

print(new,'\n') -> [1.5, 2.5, 3.5, 4.5] and 2nd, print(experiment) -> [1, 1.5, 2.5, 3.5, 4.5, 2, 3, 4, 5]

But I want it to be [1,1.5,2,2.5,3,3.5,4,4.5,5] I know I can use merge and sort, but I don't want to because I am working with a MUCH MUCH bigger list and it can't be sorted. This is just my baby list for right now.

I am really close I can feel it, it's like a sixth sense... Any help and guidance is much appreciated. Thanks a lot cutie


Solution

  • Inserting into the middle of a list a bunch of times is going to be very slow for a large dataset. It seems like you can just build a new list like you're doing:

    first = [1, 2, 3, 4, 5]
    second = []
    for i in range(0, len(first) - 1):
        avg = (first[i] + first[i+1]) / 2
        second.append(first[i])
        second.append(avg)
    second.append(first[-1])
    
    print(second)
    

    Which prints:

    [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]