def change_array(array):
main_array = array
alpha_array = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for a in main_array:
print(main_array, a)
if a == 1:
main_array = alpha_array if main_array is array else array
change_array([1, 1, 0, 0, 0, 1, 0])
output :
[1, 1, 0, 0, 0, 1, 0] 1
['a', 'b', 'c', 'd', 'e', 'f', 'g'] 1
[1, 1, 0, 0, 0, 1, 0] 0
[1, 1, 0, 0, 0, 1, 0] 0
[1, 1, 0, 0, 0, 1, 0] 0
[1, 1, 0, 0, 0, 1, 0] 1
['a', 'b', 'c', 'd', 'e', 'f', 'g'] 0
In the above program, I am trying to change the main array, which is array, with alpha array when the condition is satisfied. Apprently the main array is changing to alpha array but the main array in for loop is still array, Why is it happening?
CodePudding user response:
Consider this desired behavior:
>>> tmp = [1,2,3,4,5]
>>> tmp2 = [6,7,8,9]
>>> for a in tmp:
... print(a, tmp)
... tmp = tmp2
...
1 [1, 2, 3, 4, 5]
2 [6, 7, 8, 9]
3 [6, 7, 8, 9]
4 [6, 7, 8, 9]
5 [6, 7, 8, 9]
vs this current behavior (stated in question):
>>> tmp5 = tmp
>>> for a in tmp5:
... print(a, tmp5)
... tmp = tmp2
...
1 [1, 2, 3, 4, 5]
2 [1, 2, 3, 4, 5]
3 [1, 2, 3, 4, 5]
4 [1, 2, 3, 4, 5]
5 [1, 2, 3, 4, 5]
In your example main_array
is actually a reference to the array
object. Hence these two are equivalent: for item in main_array:
= for item in array:
Since only main_array is being modified the original reference to the object, the array variable is still present and holds the original value which the loop is referring too. This is why it iterates over the original list rather than the updated one.
CodePudding user response:
the loop copies the array to loop over it so changing it has no effect on the copy
for it to work like you want change it to this
def change_array(array):
main_array = array
alpha_array = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for a in range(len(main_array)):
print(main_array, main_array[a])
if main_array[a] == 1:
main_array = alpha_array if main_array is array else array
change_array([1, 1, 0, 0, 0, 1, 0])
this counts up to the length of main_array
in the variable a
which can then be used to index main_array