0

I need to remove the elements of the list which are greater than 1

a = [1, 2, 3, 4]

for i in a:
if i>1:
    a.remove(i)
    print(a)

If I run this code it is giving [1,3]

But when I run the second code:

for i in a[::1]:
if i>1:
    a.remove(i)
    print(a)

it is giving output [1]

Why I am facing problem with the first code?

fdermishin
  • 3,519
  • 3
  • 24
  • 45
Avijit Kar
  • 19
  • 1
  • 6

4 Answers4

2

You're modifying the list while you iterate over it. That means that the first time through the loop, I> 1, so I>1 is removed from the list. Then the for loop goes to the third item in the list, which is not 3, but 4! Then that's removed from the list, and then the for loop goes on to the third item in the list, which is now 4. And so on. Perhaps it's easier to visualize like so, with a ^ pointing to the value

Check the visualization of what's happening

[1, 2, 3, 4, 5, 6]
    ^
[1, 3, 4, 5, 6]
       ^
[1, 3, 5, 6]
          ^
[1, 3, 5]

For this example i>1 condition meets element 2 and removes it but 3 replaces the 2nd position of 2. Thus 3 is getting a skip to remove. This way 5 also skip and the final output will be like

[1, 3, 5]

To avoid this way of removing you can set a condition to skip the element you need to remove and append the elements into a new list that you don't need to delete like:

ls = [i for i in a if i <= 1]
print(ls)
mhhabib
  • 2,975
  • 1
  • 15
  • 29
0

On the first iteration, the first value is 1, so 1 > 1 which false no change is list[1, 2, 3, 4], then it goes to the second value which is 2, bcz 2 > 1, 2 will remove from the list,so your new list will looks like [1, 3, 4], then it will go to the 3rd item in the updated list which is 4 not 3 so it will remove 4 and exit the for loop,

0

It is tempting to modify a list while iterating over it. But it is always a best practice to create a new list.

 import math
 raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
 filtered_data = []
 for value in raw_data:
     if not math.isnan(value):
         filtered_data.append(value)

 filtered_data

output: [56.2, 51.7, 55.3, 52.5, 47.8]

Source: Python documentation https://docs.python.org/3.9/tutorial/datastructures.html

Aadesh Dhakal
  • 412
  • 6
  • 17
0

a = [1, 2, 3, 4]

if you remove the element during iteration, then its elements position is changed.

After second iteration the value of i is 2, then the given list becomes [1, 3, 4] And during the third iteration value of i is not 3, it is 4(so it will be deleted)

The final output will be be [1, 3]

Akhil
  • 16
  • 1
  • 4