Skip to content
Advertisement

pop/remove items out of a python tuple

I am not sure if I can make myself clear but will try.

I have a tuple in python which I go through as follows (see code below). While going through it, I maintain a counter (let’s call it ‘n’) and ‘pop’ items that meet a certain condition.

Now of course once I pop the first item, the numbering all goes wrong, how can I do what I want to do more elegantly while removing only certain entries of a tuple on the fly?

for x in tupleX:
  n=0
  if (condition):
     tupleX.pop(n)
  n=n+1

Advertisement

Answer

ok I figured out a crude way of doing it.

I store the “n” value in the for loop when condition is satisfied in a list (lets call it delList) then do the following:

    for ii in sorted(delList, reverse=True):
    tupleX.pop(ii)

Any other suggestions are welcome too.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement