Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterative deletion from list (Python 2)

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
like image 968
zxz Avatar asked Dec 12 '12 23:12

zxz


People also ask

Can you remove from a list while iterating Python?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

What are the two methods for removing items from a list in Python?

The pop() method removes an element from the list based on the index given. The clear() method will remove all the elements present in the list.

How do I remove all occurrences from a list in Python?

Python3. Method 3 : Using remove() In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list.


1 Answers

One problem here is that i is the item from the list, not it's index. So when you do del fiblist[i] you are not removing i, but the value that is at index i (which doesn't exist so you get an error). This can be fixed by using enumerate() 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:

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

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.

like image 89
Gareth Latty Avatar answered Oct 21 '22 03:10

Gareth Latty