Reputation: 11
I have a list which has tuple element. I need to modify the tuple element.
list1 = [1, (2, 'A'), 'B']
I need to modify 'A' to 'Z'
Thanks in Advance!
My solution is:
list1[1] = list(list1[1])
list1[1][1] = 'Z'
list1[1] = tuple(list1[1])
Is there any other feasible solution for this?
Upvotes: 1
Views: 35
Reputation: 1048
Tuples are immutable, so you can either convert the tuple to a list, replace the element in the list and convert it back to a tuple.
Or construct a new tuple by concatenation.
Upvotes: 0
Reputation: 2895
Generally speaking, a tuple is an immutable object - i.e. one that can't be changed. Instead, you're creating a new tuple using (part of) the data from the old tuple.
So, you can write your code in a way that reflects this:
list1[1] = (list1[1][0],'Z')
Upvotes: 1