Edwin Jose
Edwin Jose

Reputation: 11

Modify tuple element inside a list

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

Answers (2)

bart
bart

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

Itamar Mushkin
Itamar Mushkin

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

Related Questions