Home > Blockchain >  The del function in the for loop removes every second element. I want to delete all of them until th
The del function in the for loop removes every second element. I want to delete all of them until th

Time:04-12

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]

CodePudding user response:

a = [0,0,0,0,0,0,0,0,0,1,2,3,4]
n= []
for i in range(len(a)):
    if(a[i]<3):
        continue
    else:
        n.append(a[i])
print(n) # [3,4]

CodePudding user response:

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]
  • Related