Search code examples
pythonlistlist-comprehensionindex-error

Divide elements of a list by integer with list comprehension: index out of range


I am trying to divide all the elements of a list filled with integers by another integer (functionality like in numpy arrays) by list comprehension, like so:

results = 300 * [0]
for i in range(100):
    for j in range(300):
        results[j] += random.randrange(0,300)
average_results = [results[x] / 100 for x in results]

However, if I run this in Python, it throws an

IndexError: list index out of range

I have worked around this by using a regular for loop:

average_results = []
for x in results:
    average_results.append(x/100)

which works like a charm.

However, in my mind the two approaches should yield the same results, so I am totally stunted as to why it does not work.

Can someone point me in the right direction?


Solution

  • The problem is with:

      [results[x] / 100 for x in results]
    

    Here you are iterating over values in the results list (for x in results). And then for each of them trying to access the element with this index. What you rather meant was:

     [x / 100 for x in results]
    

    In other words - the "for ... in ..." part of list comprehension works with values in the list, not their indices.

    BTW, your [x / 100 for x in results] won't give you an average of all values. It will "only" take each of them and divide by 100.