Home > OS >  remove even elements from a list. Showing list index out of range
remove even elements from a list. Showing list index out of range

Time:12-06

image please refer to the image. I want to create a list(say [1,2,3,4,5]). The code checks the divisibility by 2 of every element of the list one by one. if it is divisible by 2, it removes the those elements and returns a list of odd numbers . Please try to keep the code as simple as possible as i am just a beginner....

CodePudding user response:

I took a look at the image and couldn't figure out much. Going by your definition

l = [1,2,3,4]

for i in l:
    if i % 2 == 0:  # check if i is divisible by 2
         l.remove(i)  # remove the item if the number passes above check.

CodePudding user response:

It's a lot easier and more Pythonic to build a new list of the odd numbers than it is to modify the original list to remove the even numbers.

If you understand list comprehensions, there's a simple answer.

l = [1, 2, 3, 4, 5]
l2 = [x for x in l if x%2 == 1]
print(l2)

You can also do it imperatively:

l = [1, 2, 3, 4, 5]
l2 = []
for x in l:
    if x%2 == 1:
        l2.append(x)
print(l2)

Either solution will print [1, 3, 5].

CodePudding user response:

The problem with your code is that once you remove the even number from the list, It reduces the length of the list. So in the second iteration of your code, 2 is removed from the list l = [1,2,3,4,5] which modifies the list l to [1,3,4,5], so now, the length of the list is 4 instead of 5. But the for loop, which will run for the values "0, 1, 2, 3, 4" (because of variable x, which is 5), your code produces that error. To solve this error, you can create a new list and append the even numbers in it.

CodePudding user response:

l = [1,2,3,4,5]
x = len(l)
new_l = []
for a in range(x):
    if l[a]%2!=0:
        new_l.append(l[a])
new_l

Use the above code instead of removing elements from list create a new one.

  • Related