Suppose that I have tuples of the form[(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
Then how do I increment the numbers inside the tuple that they are of the form:-[(('d',1),('g',1)),(('d',1),('d',2)),(('i',1),('g',1))]
?
I am able to do this in a single for loop. But I am looking for shorter methods.
P.S. You are allowed to create new tuples
The answer to this is Yes. Let's discuss certain ways in which this can be achieved. Method #1 : Using Access methods This is one of the way in which edit inside objects of tuples can be performed. This occurs similar to any other container and inplace using list access method.
There's no append() or extend() method for tuples in Python. Tuples are immutable data types so you can't remove the element from it. However, you can extend the tuple using concatenate or slice method.
You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.
Adding/Inserting items in a TupleYou can concatenate a tuple by adding new items to the beginning or end as previously mentioned; but, if you wish to insert a new item at any location, you must convert the tuple to a list.
A list comprehension will do the trick:
>>> t = [(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
>>> print [tuple((a, b+1) for a, b in group) for group in t]
[[('d', 1), ('g', 1)], [('d', 1), ('d', 2)], [('i', 1), ('g', 1)]]
You can't change the values in tuples, tuples are immutable. You would need to make them be lists or create a new tuple with the value you you want and store that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With