Why I Can't Re-assign A Variable In A For Loop In Python?
Solution 1:
When you loop over a list with for i in my_list
, i
isn't bound to a list cell on each iteration. It's bound to the object the list cell referred to. Assigning a new value to i
binds i
to a new object, but there's no link between i
and the list that would cause the list cell to be affected.
An equivalent way to loop over a list would be
for index in range(len(my_list)):
i = my_list[index]
whatever_loop_body()
Hopefully, it's clearer in this formulation that i
is not an alias for the list cell. (Don't actually loop over lists like this.)
Solution 2:
Let me guess, you want to have a result like the following
[1, 2, 3, 'my_value', 'my_value']
To do this, you need to do this:
['my value' if i > 3else i foriin x]
Update
Why your code doesn't work? Because i
is not a reference to an object but a primitive value assignment. Python variable reference assignment.
Update 2
If the element of the list is an object rather than a primitive, then it seems that i
become a reference to that object.
class A:
def __init__(self, val):
self.value = val
my_list = [A(1), A(2),A(3),A(4),A(5)]
for i in my_list:
if i.value > 3:
i.value = 'my_value'print([i.value for i in my_list])
# [1, 2, 3, 'my_value', 'my_value']
Update 3
Please see some of the discussion in the comment below. In python, everything is an object. No primitive.
Ref: For Syntax
Post a Comment for "Why I Can't Re-assign A Variable In A For Loop In Python?"