Replacing a None value in a list with an index in Python

Question:

In this question I have to substitute all None values in a list with the mean of the number before and after the None value. So if i have a list with

[1, None, 3, None, 7]

The desired output is

[1, 2, 3, 5, 7]

My current code:

def substitution(L):
    
    result = []
    
    for i in L:
        if i is None:
            result.append(L[3])
            
        else:
            result.append(i)
            
    return result

list = [4, None, 6, 2, 3, None, 8, 11]
test = substitution(list)
print(test)

My output makes no sense, I only came as far as to substitute the Nones with an index but can’t figure out how to get the mean of the index before and after it and then print it.

[4, 2, 6, 2, 3, 2, 8, 11]   

The desired output is as follows:

[4, 5, 6, 2, 3, 5.5, 8, 11]

Thanks in advance 🙂

Asked By: albrit

||

Answers:

If you want to use a for loop, you can loop over the indices (the position of a given element in the list) instead of the actual elements of the list:

def substitution(L):
    
    result = []
    
    for i in range(len(L)):
        if L[i] is None:
            result.append((L[i-1] + L[i+1])/2)
            
        else:
            result.append(L[i])
            
    return result
Answered By: nathan liang
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.