0

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?

5
  • 2
    You don't have a list of variables. You have a list of values. Read nedbatchelder.com/text/names.html. Commented Mar 25, 2019 at 16:19
  • You need to update the list itself, not a single item of the list. Commented Mar 25, 2019 at 16:21
  • Related (the opposite problem, basically): How to update a list of variables in python? Commented Mar 25, 2019 at 16:29
  • @deceze Those duplicates certainly solve the OP's problem, but they do nothing to explain why the OP's code doesn't work. The OP specifically asked why the code doesn't work. I think this should be reopened. (I tried to find a better duplicate, but couldn't.) Commented Mar 25, 2019 at 16:31
  • @deceze Any objections to me reopening the question? Commented Mar 25, 2019 at 19:37

2 Answers 2

3

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] = ""
Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.