a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for i in a:
if a[i] % 2 == 0 :
l.append(a[i])
The code above keeps throwing the error - "IndexError: list index out of range"
I cannot understand what to do ?
When you perform for i in a you are iterating over the elements of a, not the indices!
You are trying to access: a[1] and then a[4] and then a[9] and then a[16] -> Which is the one that is causing the IndexError.
If you want to iterate only over the indices try:
>>> for i in range(len(a)):
if a[i] % 2 == 0 :
l.append(a[i])
>>> print (l)
[4, 16, 36, 64, 100]
If you need both the value and index use for index, value in enumerate(a):.
When you are iterating over a, you are looking at the value rather than the position of that value in the list.
You could use just the value like so:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for val in a:
if val % 2 == 0 :
l.append(val)
Or alternately, if you need both the position and the value then you can use the enumerate function, like so:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for pos, val in enumerate(a):
if a[pos] % 2 == 0 :
l.append(a[pos])
You could use list comprehension for that:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l = [i for i in a if i%2 == 0]
print(l)
[4, 16, 36, 64, 100]
as in other answers, i takes the values from a, which are [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
in the loop when i takes the value "16", a[i] will be out of range!! (16 > len(a))
for debugging i always suggest printing...
in this case if you print the value ofi in the loop, you will find the problem yourself
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for i in a:
if a[i] % 2 == 0 :
l.append(a[i])
...
if a[1] % 2 == 0:
...
if a[4] % 2 == 0:
...
if a[9] % 2 == 0:
...
if a[16] % 2 == 0:
index error, because the biggest index is 9 in array a... so u have to use this:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for i in a:
if i % 2 == 0 :
l.append(i)
or this example:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for i in a:
if i % 2 == 0 :
l.append(i)
or the 1 line solution:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= [x for x in a if x%2 == 0]