Home > Back-end >  Is there a way to insert values into a list of tuple in Python?
Is there a way to insert values into a list of tuple in Python?

Time:11-12

I have a empty list of tuple and I wish to enter values inside that tuple.

The desired output is :

lst = [()] --> lst = [(1,2,'string1','string2',3)]

CodePudding user response:

you can't, A tuple is a collection that is ordered and immutable.

though, you can create a new tuple with the same name

CodePudding user response:

A tuple is, by definition, unchangable.
You may want to replace that tuple with a new one like this:

lst = [()]
lst[0] = ("item1", "item2")

In this way you are replacing the origina tuple with a new one with the desired items. If the tuple is not empty you can do:

lst[0] = (*lst[0], "new item")

Here you are unpacking the values of the old tuple (*lst[0] is equal to "item1", "item2" in this example) and adding new items.

Note that if you are working with variable data maybe tuple is not the best data structure to use in this case.

  • Related