Reputation: 801
Suppose we have a list variables
with the variables [a, b, c]
. The code shall check if the variable value is a of type string with the text "None"
. The variable value shall be updated to ""
if true. Using a for loop, I would write:
a = 1
b = 2
c = 3
variables = [a, b, c]
for i in range(len(variables)):
variables[i] = 55
print(variables)
print(a, b, c)
This outputs:
[55, 55, 55]
1 2 3
Why don't the variables update their value?
Upvotes: 0
Views: 2489
Reputation: 1469
If I reproduce your example the variable "variable" will indeed update. However, the list of variables "variables" will not. Because you are not telling it to change.
There are several ways to change this. If this is a small list I would simply create a new list
variables = [1,2,3,4,"None",5,1,"foo","bar"]
new_variables = [0 if variable == "None" else variable for variable in variables]
Hope this helps!
Upvotes: 0
Reputation: 532333
All you are doing is overwriting the value of the local variable variable
, not an element in variables
. You'll need to iterate over the indices and assign to variables[i]
directly:
for i, value in enumerate(variables):
if value == "None":
variables[i] = ""
Upvotes: 3