sebko_iic
sebko_iic

Reputation: 340

For each loop, update variable

I have an assignment where I have to implement code stubs. A simplified version basically is:

for a,b in zip(var_a,var_b):
   # implementation here

I'm pretty sure the task is basically to update a with the variable b. But this would be very weird because my understanding is that a,b are just copies of var_a,var_b. So changing the values of a,b won't affect var_a,var_b. Am I right?

Of course, I could easily change the code, so I really update var_a,var_b but I don't think changing the stubs is intended, which would either mean the stub was poorly designed or I didn't understand the task correctly.

Could you please confirm that in this for loop I only have access to the copies or is there a suuper easy way to update the original variables without changing the stub?

Upvotes: 0

Views: 42

Answers (1)

Nitay Bachrach
Nitay Bachrach

Reputation: 31

a and b aren't copy of var_a and var_b, but rather they point to the first element in var_a and var_b respectively.

About changing their value - you can do it, but of course if you just reassign them it will not affect var_a or var_b. So if they are mutable - that's not the way to do it.

but for example, if var_a and var_b are list of lists, you can do something like: a.extend(b). And it will affect the list in var_a.

Read about objects mutability in python.

>>> var_a = [[1,2,3],[10,20,30]]
>>> var_b = [['a','b','c'], ['A','B','C']]
>>> for a, b in zip(var_a, var_b):
...  a.extend(b)
...
>>> var_a
[[1, 2, 3, 'a', 'b', 'c'], [10, 20, 30, 'A', 'B', 'C']]

but integers are immutable:

>>> var_a = [1,2,3]
>>> var_b = [10,20,30]
>>> for a, b in zip(var_a, var_b):
...  a += b
...
>>> var_a
[1, 2, 3]

Upvotes: 1

Related Questions