Floggedhorse
Floggedhorse

Reputation: 694

Replacing a single element in a tuple nested within a list - Is their a better way?

Edit - I want to change the value of a tuple nested in a list, at a specific position
eg changed nestedTuple[1][1] change to 'xXXXXx'

I have come up with this code, that works, but it just seems very 'Un-pure!'

I ASSuME that it would be very demanding on resources.

Could anyone please advise me if their is a better way?

>>> nestedTuple= [('a','b','c'), ('d','e','f'), ('g','h','i')]
>>> tempList = list(nestedTuple[1])
>>> tempList[1] = 'xXXXXx'
>>> nestedTuple[1] = tuple(tempList)
>>> print nestedTuple
[('a', 'b', 'c'), ('d', 'xXXXXx', 'f'), ('g', 'h', 'i')]

Upvotes: 0

Views: 1758

Answers (5)

Joop
Joop

Reputation: 8118

I understand that this is data structure that you are getting. Performance aside it would make for much cleaner and readable code to change the data to nested list, do the manipulation, and if you need to write it back to convert it back to nested tuple. May be suboptimal in terms of speed, but that might not be the limiting factor for your application.

nestedTuple= [('a','b','c'), ('d','e','f'), ('g','h','i')]
nestedList = [list(x) for x in nestedTuple]

now you can use normal list slicing and assigning

nestedList[1][1] = ['xxxxXXxxx']

if you need the data back in original nested tuple format use the one liner:

nestedTuple = [tuple(x) for x in nestedList]

most readable and least likely to contain bugs if your data structure grows and your slicing becomes more complex.

Upvotes: 0

user2841651
user2841651

Reputation:

Depending on how many changes you want to make in your nestedTuple and depending on downstream in your program. You may want to built a nestedList from your nestedTuple

nestedList = [list(myTuple) for myTuple in nestedTuple]

and then do:

nestedList[x][y] = 'truc'

and then make a new nestedTuple if needed

Otherwise you should profile this

Upvotes: 0

swamydkv
swamydkv

Reputation: 27

Very purpose to use tuples is its immutable means once the tuple is created the values cannot be changed. In your case the best way will be to use nested lists i.e., as shown below

>>> nestedList = [['a','b','c'], ['d','e','f'], ['g','h','i']]

Now to change the element 'e' in the list to 'xxxx' you can use as shown below

>>> nestedList[1][1] = 'xxxx'

Upvotes: -1

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

You can use slicing.

>>> i = 1
>>> nestedTuple = [('a','b','c'), ('d','e','f'), ('g','h','i')]
>>> nestedTuple[1] = nestedTuple[1][:i] + ('xXXXXx', ) + nestedTuple[1][i+1:]
>>> nestedTuple
[('a', 'b', 'c'), ('d', 'xXXXXx', 'f'), ('g', 'h', 'i')]

Upvotes: 1

simonzack
simonzack

Reputation: 20948

How about this?

nested_tuple[1] = tuple('XXXXX' if i==1 else x for i, x in enumerate(nested_tuple[1]))

Note that tuples aren't meant to be changed, so one liners aren't going to be very clean.

Upvotes: 1

Related Questions