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
A tuple is declared as unchangable.
And you are not gonna pop item inside itself iteration, it causes error because it changes the length of list obj. But you can do it in list comprehensions, on the opposite side.
This keeps elements that didnt match the condition rather than popping it out of the tuple/list.
But if you are intend to do it as similar as your own way, you have to make your tuple a list beforehand by sth like
listX = list( tupleX )
. youd better add the index of unwanted materials inside the iteration into a list ( unwanted_list ), and iterate unwanted_list and pop ele out in the original list. then make it back to tuple liketuple( listX )
There is a simple but practical solution.
As DSM said, tuples are immutable, but we know Lists are mutable. So if you change a tuple to a list, it will be mutable. Then you can delete the items by the condition, then after changing the type to a tuple again. That’s it.
Please look at the codes below:
For example, the following procedure will delete all even numbers from a given tuple.
if you test the type of the last tuplex, you will find it is a tuple.
Finally, if you want to define an index counter as you did (i.e., n), you should initialize it before the loop, not in the loop.
As
DSM
mentions,tuple
's are immutable, but even for lists, a more elegant solution is to usefilter
:or, if
condition
is not a function, use a comprehension:if you really need tupleX to be a tuple, use a generator expression and pass that to
tuple
:Yes we can do it. First convert the tuple into an list, then delete the element in the list after that again convert back into tuple.
Demo:
Thanks
Maybe you want dictionaries?
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:
Any other suggestions are welcome too.