Home > Enterprise >  assign value to a variable in a list in Python
assign value to a variable in a list in Python

Time:08-01

I have a list of lists in the format

list = [["text1",index_value1],["text2",index_value2],["text3",index_value3]]

In a for loop I want to assign values to index_value1, index_value2, ...

If I do

list[0][1] = 5

I would replace index_value1 in the list with 5 instead assigning the value 5 to index_value1. How can I assign the value to the variable instead of replacing the variable in the list.

I could change the list to

list = [["text1","index_value1"],["text2","index_value2"],["text3","index_value3"]]

If this simplifies the solution.

Thanks for any help

CodePudding user response:

How do you want a assign a variable like a array or an dictionary ? without that it replace the indexvalue variable with a value you provided.

` index_value1 = None

index_value2 = None

index_value3 = None

list1 = [["text1",index_value1],["text2",index_value2],["text3",index_value3]]

for val in list1:

val[1] = 5

print(list1) `

CodePudding user response:

This is a workaround using Python dictionary, as you cannot assign a value to a variable in a list without declaring it first.

dict = {
  0: {"id": "text1", "index_value1": None},
  1: {"id": "text2", "index_value2": None},
  2: {"id": "text3", "index_value3": None}
}

To assign a value:

dict[0]["index_value1"] = 5
  • Related