-3

Sorry for asking this question. This is simple python program

odd = lambda x : bool(x % 2)
numbers = [n for n in range(10)]
print numbers
for i in range(len(numbers)):
    if numbers[i]%2!=0:
        del numbers[i]
    print numbers

I am getting error while running this program Traceback (most recent call last): File "test.py", line 5, in <module> if numbers[i]%2!=0: IndexError: list index out of range

I tried many thing but nothing is working, Can any one help me

sudeep Krishnan
  • 668
  • 1
  • 6
  • 23

3 Answers3

3

Notes:

If you really NEED TO DELETE THE LIST WHEN LOOPING you could loop the list in reverse and delete the elements it will not stop the iteration since it will delete the element in normal direction (left --> right) and the loop is in opposite direction (right-->left)

Code:

odd = lambda x : bool(x % 2)
numbers = [n for n in range(10)]
print numbers
for i in numbers[::-1]:
    print i
    if i%2!=0:
        del numbers[numbers.index(i)]
print numbers

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9
8
7
6
5
4
3
2
1
0
[0, 2, 4, 6, 8]

Or to be even more simple how about a list comprehension and your lambda function

Code1:

[num for num in numbers if not odd(num)]

Output1:

 [0, 2, 4, 6, 8]
The6thSense
  • 8,103
  • 8
  • 31
  • 65
2
b = range(10)
a = [i for i in b if not i%2]

print a
huang
  • 521
  • 3
  • 11
1
 odd = lambda x : bool(x % 2)
    numbers = [n for n in range(10)]
    print numbers
    for i in range(len(numbers)):
        try:
            if numbers[i]%2!=0:
               del numbers[i]
                print numbers
        except IndexError:
            pass