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?
you can use one of these at the end:
the problem is you're trying to access to an index that does not exist (x is the value there not the index)
Your array is filled with random integer values, ranging from 0 to 29999. In your list comprehension you make, as far as I can see, a mistake here:
x
is already the value in the array, i.e. the random integer. You get theIndexError
becauseresults[29999]
is, for example, one of the possible calls there.What you want instead is to not use
x
as an index:This should be straight forward and possible.
The problem is with:
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: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.This is the equivalent list comprehension to your loop:
x
is already the value formresults
. Don't index again into it withresults[x]
.