Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 !

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading