Search code examples
python-3.xfor-loopdel

The del function in the for loop removes every second element. I want to delete all of them until the condition is met


a = [0,0,0,0,0,0,0,0,0,1,2,3,4,0,0]

for i in a: if i < 3: del a[0]

print(a) [0, 0, 0, 1, 2, 3, 4]

should be:

[3,4,0,0]


Solution

  • You are using i in a confusing way, since you're not using it as an index (which is kinda the norm) but as an iterator. Just for readability I would suggest changing the iterator name to something more descriptive.

    If I understand you're question correctly, you want to delete the first element, until it is bigger or equal 3. If that is your question, you could do it like this:

    a = [0,0,0,0,0,0,0,0,0,1,2,3,4,0,0]
    while a[0]<3:
        del a[0]
    print(a) # [3,4,0,0]