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]
>Solution :
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 !