Skip to content Skip to sidebar Skip to footer

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] fo

Solution 1:

The problem is with:

  [results[x] / 100for 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.

Solution 2:

This is the equivalent list comprehension to your loop:

average_results = [x / 100 for x in results]

x is already the value form results. Don't index again into it with results[x].

Solution 3:

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:

results[x]

x is already the value in the array, i.e. the random integer. You get the IndexError because results[29999] is, for example, one of the possible calls there.

What you want instead is to not use x as an index:

average_results = [x / 100 for x in results]

Solution 4:

you can use one of these at the end:

1. average_results = [results[x] / 100 for x in range(len(results))]
2. average_results = [x / 100 for x in results]

the problem is you're trying to access to an index that does not exist (x is the value there not the index)

Solution 5:

This should be straight forward and possible.

In [1]: results = 10 * [10]

In [2]: [_/10 for _ in results]
Out[2]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Post a Comment for "Divide Elements Of A List By Integer With List Comprehension: Index Out Of Range"