# Inserting elements within a list in Python

## Question:

I have a list `A` with first and last elements `20` and `0` respectively. I am inserting elements in `A` through `C` but I want to do so in one step and without writing everything manually.

``````len_A=6
A=[20,0]
B=A[0]/(len_A-1)
C=[A[0],A[0]-B, A[0]-2*B,A[0]-3*B,A[0]-4*B,0]
print(C)
``````

The current and expected output is

``````[20, 16.0, 12.0, 8.0, 4.0, 0]
``````

Easiest solution would be using numpy.linspace, but you can also achieve the same by figuring out the mathematical formula for what you are trying to achieve.

``````from numpy import linspace

len_A=6
A=[20,0]

C = linspace(A[0], A[1], len_A) # using numpy.linspace

print(C)

C = [A[0] - ((A[0] - A[1]) * i)/(len_A-1) for i in range(len_A-1)] + [A[1]] # pure maths

print(C)
``````

You can try the below:

``````len_A = 6
A = [20, 0]
B = A[0] / (len_A - 1)
C = [A[0] - i * B for i in range(len_A)]
print(C)
``````

Output:

``````[20, 16.0, 12.0, 8.0, 4.0, 0]
``````
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.