1

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?

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
Edwin Jose
  • 11
  • 1
  • Calling your variable `list1` kinda makes it less readable... why not `my_list`? – Itamar Mushkin Jul 07 '19 at 06:51
  • 3
    Possible duplicate of [Python: changing value in a tuple](https://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple) – Austin Jul 07 '19 at 06:55

2 Answers2

1

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')
Itamar Mushkin
  • 2,803
  • 2
  • 16
  • 32
0

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.

bart
  • 1,003
  • 11
  • 24