Python tuples are immutable then how we can add values to them?

PythonServer Side ProgrammingProgramming

Python tuple is an immutable object. Hence any operation that tries to modify it (like append/insert) is not allowed. However, following workaround can be used.

First, convert tuple to list by built-in function list(). You can always append as well as insert an item to list object. Then use another built-in function tuple() to convert this list object back to tuple.

>>> T1=(10,50,20,9,40,25,60,30,1,56)
>>> L1=list(T1)
>>> L1
[10, 50, 20, 9, 40, 25, 60, 30, 1, 56]
>>> L1.append(100)
>>> L1.insert(4,45)
>>> T1=tuple(L1)
>>> T1
(10, 50, 20, 9, 45, 40, 25, 60, 30, 1, 56, 100)



raja
Published on 14-Jan-2018 20:03:51
Advertisements