MarkF6
MarkF6

Reputation: 503

Python: Modify tuple in list

My actual output looks like this:

target = [([('Kid', '200-5'), (u'Rock', '200-6')], u's725')]

How can I modify data in the tuple such that I can return, at the end, the modified list which has the same format as target?

For example: I'd like to change 'kid' in 'adult', such that the rest stays, i.e. I receive: newTarget = [([('adult', '200-5'), (u'Rock', '200-6')], u's725')]

My idea: Copy all the data of target in a temporary list, modify things and create the same format as in target.

BUT: How can I achieve this concretely? Until now, I could Change and modify things, but I didn't get the same format again...

Upvotes: 1

Views: 546

Answers (3)

Anthony Kong
Anthony Kong

Reputation: 40624

You will need recursion if you need to be more flexible

target = [([('Kid', '200-5'), (u'Rock', '200-6')], u's725')]

def search_and_replace(inlist):
        res = []
        for t in inlist:
            if isinstance(t, list):
                res.append(search_and_replace(t))
            elif isinstance(t, tuple):
                t1, t2 = t 
                if t1 == 'Kid':
                    t1 = 'adult'
                elif isinstance(t1, list):
                    t1 = search_and_replace(t1)
                res.append((t1, t2)) 
            else:
                res.append(t)

        return  res 


print search_and_replace(target) 

Upvotes: 0

Marc Tudurí
Marc Tudurí

Reputation: 1949

Have you tried this?

l = list(target[0][0][0])
l[0] = 'Adult'
target[0][0][0] = tuple(l)

Upvotes: 4

Mattie B
Mattie B

Reputation: 21269

Since tuples are immutable, you cannot modify their elements—you must replace them with new tuples. Lists are mutable, so you can replace individual parts as needed:

>>> x = [(1, 2), (3, 4), 5]
>>> x[0] = (x[0][0], 0)
>>> x
[(1, 0), (3, 4), 5]

In the above example, I create a list x containing tuples as its first and second elements and an int as its third. On the second line, I construct a new tuple to swap in to the first position of x, containing the first element of the old tuple, and a new element 0 to replace the 2.

Upvotes: 1

Related Questions