Home > other >  Python for each element in a list add the value of previous index and next index
Python for each element in a list add the value of previous index and next index

Time:12-01

For each element in a list I want to add the value before and after the element and append the result to an empty list. The problem is that at index 0 there is no index before and at the end there is no index next. At index 0 I want to add the value of index 0 with value of index 1, and in the last index I want to add the value of the last index with the same index value. As following:

vec = [1,2,3,4,5]
newVec = []

for i in range(len(vec)):
    newValue = vec[i]   vec[i 1]   vec[i-1]
    # if i   1 or i - 1 does now exist pass 
    newVec.append(newValue)

 Expected output: newVec = [1 2, 2 1 3, 3 2 4,4 3 5,5 4]

 # newVec = [3, 6, 9, 12, 9]

CodePudding user response:

You can make the conditions inside the for loop

for i in range(len(vec)):
    if i == 0 :
        newValue = vec[i]   vec[i 1]
    elif i == len(vec)-1:
        newValue = vec[i]   vec[i-1]
    else:
        newValue = vec[i]   vec[i 1]   vec[i-1]
    newVec.append(newValue)

print(newVec)

output:

[3, 6, 9, 12, 9]

CodePudding user response:

You have possible exceptions here, I think this code will do the trick and manage the exceptions.

vec = [1, 2, 3, 4, 5]
new_vec = []
for index, number in enumerate(vec):
    new_value = number
    if index != 0:
        new_value  = vec[index - 1]
    try:
        new_value  = vec[index   1]
    except IndexError:
        pass
    new_vec.append(new_value)

Your output will look like this:

[3, 6, 9, 12, 9]

Good luck !

CodePudding user response:

You can just add 0 to either side of vec so that it's adding nothing to create an accurate result. Then just use a for i in range(1, ...) loop, starting at value 1 to add value before and after i. This is what i got for my code:

vec = [1,2,3,4,5]
newVec = []
vec.insert(0, 0)
vec.insert(len(vec)   1, 0)
for i in range(1, len(vec) - 1):
    newVec.append(vec[i-1]   vec[i]   vec[i 1])
print(newVec)

Which creates the output of:

[3, 6, 9, 12, 9]

Hope this helps.

  • Related