-1

I've got the below code, with the aim to run through a list of defined variables and update them.

a = 1
b = 2
c = 3
test_list = [a, b, c]
print(test_list)

for i in test_list:
    i = 4

print(test_list)

When I run this though the test_list variables don't change. Any ideas what I'm doing wrong?

martineau
  • 119,623
  • 25
  • 170
  • 301
emmao453
  • 1
  • 1
  • `test_list` is not, in any sense, a "list of defined variables". It's simply the list `[1, 2, 3]` - the variables that those values came from are no longer relevant. – jasonharper Apr 06 '21 at 20:01
  • 1
    Lists don't contain *variables*. Lists contain *objects*. Variables *refer to objects*. `i = 4` just assigns an `int` object to the variable `i`, and won't affect any other variable you have. – juanpa.arrivillaga Apr 06 '21 at 20:05
  • Thanks all. Makes sense! – emmao453 Apr 06 '21 at 20:15

1 Answers1

1

Your for loop is returning you each element of the list, one at a time, in a variable called i. So, the first time through the loop, i is 1. You then change i to 4. That has nothing to do with the list.

It is possible to do what you ask:

for i in range(len(test_list)):
    test_list[i] = 4

but there are usually better ways to do that kind of thing. Tell us what you REALLY want and we can advise you.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30