Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to increment inside tuple in python?

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

like image 278
Palash Ahuja Avatar asked May 29 '15 01:05

Palash Ahuja


People also ask

Can we modify list inside a tuple?

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.

Can we extend tuple in Python?

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.

Can we add new items in tuple?

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.

Can you add numbers to a tuple?

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.


2 Answers

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)]]
like image 87
David Greydanus Avatar answered Oct 01 '22 09:10

David Greydanus


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.

like image 25
Eric Renouf Avatar answered Oct 01 '22 09:10

Eric Renouf