Reputation: 33
For example I want to remove the extra 1s and 2s in this tuple ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2') to return ('1', '2')
How can I do this?
Upvotes: 2
Views: 60
Reputation: 9994
As Alok correctly mentions, you have to create a new tuple. As Alok demonstrates, you can of course assign it to the variable that previously held the original tuple.
If you don't care about order, use set
as Alok suggests. If you however want to preserve the order (of first occurrence of each unique value), you can use a very similar trick with an OrderedDict
:
from collections import OrderedDict
# Different example to demonstrate preserved order
tp = ('2', '2', '2', '1', '1', '1', '1', '1', '1', '1')
tp = tuple(OrderedDict.fromkeys(tp).keys())
# Now, tp == ('2', '1')
Upvotes: 3
Reputation: 4219
You can do this using a set
:
a = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2')
b = tuple(set(a))
If the order is important you could sort b
.
Upvotes: 0
Reputation: 2665
They are correct, tuples in python are immutable therefore you cannot update the current tuple. This function loops through data creating a list of indexes that do not currently exist! It then returns a tuple of the list! Good luck!
data = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '3', '4','4')
def removeDoubles(data):
out = []
for i in data:
if i in out:
continue
out.append(i)
del data
return tuple(out)
print removeDoubles(data)
Upvotes: 0
Reputation: 3741
You can't modify tuple in place, So definitely you have to get new tuple. You can use set to remove duplicate elements.
>>> tp = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2')
>>> tp = tuple(set(tp))
>>> tp
('1', '2')
Upvotes: 4