Iterative removal from a list (Python 2)

I just started programming and I am 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 below, where I try to find the odd numbers in the list and delete them.

del fiblist[i] the following error message appears:

Traceback (last last call): File "... / euler.py", line 35, in del fiblist [i] IndexError: list destination index out of range

I do not see what I am doing wrong here, and I would really appreciate it if someone could help me understand what I am doing wrong.

 #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 
+6
source share
1 answer

One of the problems is that i is an item from a list, not an index. Therefore, when you make del fiblist[i] , you are not deleting i , but a value that is in index i (which is not there, so you get an error message). This can be fixed using enumerate() to use indexes, however this leads to a new problem.

The main problem here is that you cannot change the length of the list while iterating over as it mixes with iteration in Python. One solution would be to copy the list and work on the copy, but it is best to use the list description to do what you want:

 [i for i in fiblist if i%2 == 0] 

This creates a new list with only the items you want. The meaning of the list is a powerful tool, so I suggest you watch the video that I linked for more.

+5
source

All Articles