I’ve just started programming, and I’m solving Project Euler problems with Python for practice.
(This is problem #2, finding the sum of the even fibonacci numbers within 4 million.)
My problem appears in the loop at the bottom, where I’m trying to locate the odd numbers in the list, and delete them.
del fiblist[i] gives me the following error message:
Traceback (most recent call last):
File “…/euler.py”, line 35, in
del fiblist[i]
IndexError: list assignment index out of range
I don’t see what I’m doing wrong here, and would really appreciate if anyone could help me see what I’m doing wrong here.
#euler2
def fibonacciList(limit):
'''generates a list of fib numbers up to N'''
mylist = []
a,b = 1,2
while True:
if a <= limit:
mylist.append(a)
a,b = b,a+b
else:
break
return mylist
fiblist = fibonacciList(4000000)
for i in fiblist:
if i%2 != 0: #if not even, delete from list
print i
del fiblist[i]
print fiblist
One problem here is that
iis the item from the list, not it’s index. So when you dodel fiblist[i]you are not removingi, but the value that is at indexi(which doesn’t exist so you get an error). This can be fixed by usingenumerate()to get indices to use, however, doing so introduces a new problem.The main issue here is that you can’t modify the length of a list while you iterate over it, as it messes with Python’s iteration. One solution would be to copy the list and work on a copy, but the better one is to use a list comprehension to do what you want:
This produces a new list with only the elements you want in. List comprehensions are a powerful tool, so I suggest you watch the video I linked for more.