Hi all,

Ive been working on this little piece of code down there that removes the odd numbers from a list of numbers. I get an "IndexError: list index out of range" whenever I try to run it. From what I understand, it means that l is attempting to use the number at position i that doesn't exist.

def del_odd(l):
  for i in range(0,len(l)):
    if l[i]%2 != 0:
      l.remove(l[i])
  return l

I may have completely misunderstood the error, but could someone offer up a small nugget of wisdom?

It might be a tall order, but try to just point me in the right direction instead of just giving me the code outright as I still want to try to learn this myself.

Cheers guys!

Recommended Answers

All 4 Replies

when you do

l.remove(l[i])

, your list 'l' reduces in size, so at some point, l will give error because the index doesn't exist.

A rule that can be good to remember.
Never delete something from or add something to the list you are iterating over.

The solution is:
Iterate over your original list, and put everything which passes your test into another list.

Some way of doing this.
Using List comprehensions.

>>> l = [1,2,3,4,5,6,7,8]
>>> odd_remove = [item for item in l if item %2 != 1]
>>> odd_remove
[2, 4, 6, 8]
>>>
l = [1,2,3,4,5,6,7,8]

even_list = []
for item in l:
    if item %2 != 1:
        even_list.append(item)

print even_list  #[2, 4, 6, 8]
l = [1,2,3,4,5,6,7,8]

for item in l[:]: #make a copy of list
	if item %2 != 0:
	    l.remove(item)

print l  #[2, 4, 6, 8]

A rule that can be good to remember.
Never delete something from or add something to the list you are iterating over.

The solution is:
Iterate over your original list, and put everything which passes your test into another list.

Some way of doing this.
Using List comprehensions.

>>> l = [1,2,3,4,5,6,7,8]
>>> odd_remove = [item for item in l if item %2 != 1]
>>> odd_remove
[2, 4, 6, 8]
>>>
l = [1,2,3,4,5,6,7,8]

even_list = []
for item in l:
    if item %2 != 1:
        even_list.append(item)

print even_list  #[2, 4, 6, 8]
l = [1,2,3,4,5,6,7,8]

for item in l[:]: #make a copy of list
	if item %2 != 0:
	    l.remove(item)

print l  #[2, 4, 6, 8]

Oh, I forgot to mention that I can't copy over another list. I have to do all of it with that 1 list.

Sorry guys.

Oh, I forgot to mention that I can't copy over another list. I have to do all of it with that 1 list.

Sorry guys.

Then start with the end of the list

def del_odd(l):
  for i in range(len(l)-1, -1, -1):
    if l[i] % 2 != 0:
      del l[i]

Notice that l is a bad variable name. Also try to understand the difference between l.remove(l[i]) (bad) and del l[i] (good).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.