0

This function returns a ListIndex error on line 8. I try to calculate the sum of all squared values in the nList:

def oneVolume(n):
  j = 0
  Sum = 0
  nList = []
  for i in range (n):
    nList.append(2*random()-1)
    while j <= n:
      Sum = Sum +nList[j] # line with list index error
      j = j+1
  return Sum
4
  • are you just trying to sum nList? Try sum(nList). Commented Mar 1, 2014 at 2:06
  • i want to square each value in the list and then sum all the squared values Commented Mar 1, 2014 at 2:08
  • @user3349164 sum([x**2 for x in nList]) Commented Mar 1, 2014 at 2:10
  • @user3349164 or in similar flavor as @loki, sum(map(lambda x: x**2, nList)) Commented Mar 1, 2014 at 2:13

2 Answers 2

2
while j <= n:

Should be

while j < n;

range(5) == [0, 1, 2, 3, 4]. There is no 5 element (but there are five elements, because there's a 0)


But this isn't the pythonic approach. Iterate over the list instead of a range the size of the list:

def oneVolume(n):
    Sum = 0
    nList = []
    for i in range(n):
        nList.append(2*random()-1)
    for j in nList:
        Sum = Sum + j
    return Sum

But you can go a whole lot further in simplifying, using a generator and the built-in sum function:

def oneVolume(n):
    return sum(2*random()-1 for _ in range(n))

The generator is a lot like a list, [2*random()-1 for _ in range(n)], only more transient. That gets passed to the sum, which automatically does what you intended by the second half of your function.

Sign up to request clarification or add additional context in comments.

Comments

0

You have an off by 1 error.

l = []
l.append(1)
l.append(2)
l.append(3)

l will that 3 elements. They will be l[0] (containing 0), l[1], and l[2]

len(l) will be 3

referencing l[3] will be an index out of bounds.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.