pop/remove items out of a python tuple
As DSM
mentions, tuple
's are immutable, but even for lists, a more elegant solution is to use filter
:
tupleX = filter(str.isdigit, tupleX)
or, if condition
is not a function, use a comprehension:
tupleX = [x for x in tupleX if x > 5]
if you really need tupleX to be a tuple, use a generator expression and pass that to tuple
:
tupleX = tuple(x for x in tupleX if condition)
In Python 3 this is no longer an issue, and you really don't want to use list comprehension, coercion, filters, functions or lambdas for something like this.
Just use
popped = unpopped[:-1]
Remember that it's an immutable, so you will have to reassign the value if you want it to change
my_tuple = my_tuple[:-1]
Example
>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)
If you want to have the popped value,,
>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
>>> foo, bit = foo[:-1], foo[-1]
>>> bit
1
>>> foo
(3, 5, 2, 4, 78, 2)
Or, to work with each value of a tuple starting at the back...
foo = 3,5,2,4,78,2,1
for f in reversed(foo):
print(f) # 1; 2; 78; ...
Or, with the count...
foo = 3,5,2,4,78,2,1
for f, i in enumerate(reversed(foo)):
print(i, f) # 0 1; 1 2; 2 78; ...
Or, to coerce into a list..
bar = [*foo]
#or
bar = list(foo)
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:
my_tuple = (10, 20, 30, 40, 50)
# converting the tuple to the list
my_list = list(my_tuple)
print my_list # output: [10, 20, 30, 40, 50]
# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position
# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]
# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)
print my_tuple # output: (10, 30, 40)
Thanks