how to increment inside tuple in python?

13,189

Solution 1

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)]]

Solution 2

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.

Solution 3

This is the least pythonic way but the most explanatory.

Split into lists, add values to the integer list, then zip them back together:

valued = []
lettered = []
plusone = []
listed = [(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
for x,y in listed:
    for subx, suby in x,y:
        valued.append(int(suby))
        lettered.append(subx)
for value in valued:
    value = value + 1
    plusone.append(int(value))
#print plusone
coolness = zip(lettered,plusone)
print coolness
exit()

The results are: [('d', 1), ('g', 1), ('d', 1), ('d', 2), ('i', 1), ('g', 1)]

Share:
13,189

Related videos on Youtube

Palash Ahuja
Author by

Palash Ahuja

Updated on September 15, 2022

Comments

  • Palash Ahuja
    Palash Ahuja over 1 year

    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

  • Navith
    Navith almost 9 years
    The tuples are in a list according to the question.
  • Eric Renouf
    Eric Renouf almost 9 years
    @Navith Right, but the tuples themselves still cannot be changed, it doesn't matter whether or not they are in a list
  • Palash Ahuja
    Palash Ahuja almost 9 years
    You are allowed to create new tuples and store them
  • Navith
    Navith almost 9 years
    But you can change the list (through [:] =) to use new tuples with the second value incremented.
  • Palash Ahuja
    Palash Ahuja almost 9 years
    Please elaborate @Navith
  • Eric Renouf
    Eric Renouf almost 9 years
    @Navith that's what I was trying to say, what part of it doesn't say that? you cannot change the tuples, but you can "create a new tuple with the value you want and store that" as I said
  • David Greydanus
    David Greydanus almost 9 years
    "I am able to do this in a single for loop. But I am looking for shorter methods." This is not shorter...
  • james-see
    james-see almost 9 years
    @DavidGreydanus whoops, I swear that wasn't in the question at first.
  • DaHoC
    DaHoC almost 3 years
    For newer Python versions 3+, print requires parentheses: print( [tuple((a, b + 1) for a, b in group) for group in t] )