pythonpython-2.7binomial-theorem

Finding the expectation of 2 consecutive elements in a list


I have

mylist = [a, b, c, d] 

and I want to get:

[p*a+(1-p)*b, p*b+(1-p)*c, p*c+(1-p)*d]

right now what I am doing is this:

somelist = []   
for i in range(len(mylist)):
    if i+1<len(mylist):
        expectedVal = (1-p)*mylist[i]+p*mylist[i+1]
        somelist.append(expectedVal)

is there a cleverer way to not get an "out of index" exception when the loop goes for its last iteration?


Solution

  • To my mind, the simplest modification to your code would be to iterate up to one less than the length of mylist:

    for i in range(len(mylist)-1):
        expectedVal = (1-p)*mylist[i]+p*mylist[i+1]
        somelist.append(expectedVal)