Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change object variables in for loop in python

I'm not sure, whether it's an easy problem with easy solution or it's something that needs to dig a little deeper.

Let's say I have an object Item with variables Item.a and Item.b. Now I have two instances of these objects: Item1 and Item2

What I need is something like this:

for (value_1, value_2) in [(Item1.a, Item2.a), (Item1.b, Item2.b)]:
    if value_1 != value_2:
        value_1 = value_2

Of course this one is only an example of more complex problem. The substitution is ok, it finds differences between objects and substitutes them. The problem is, that all the time I'm doing it on copies of those variables, not on object references. As soon as it finish the loop, I can print both Item1 and Item2 and they are the same as before loop.

Is there any possibility to pass references into a loop? I know how to do it with lists, but I could not find an answer to objects.

like image 670
Gandi Avatar asked Jul 28 '11 08:07

Gandi


People also ask

How do you change a variable value in a loop in Python?

If you put i = 4 then you change i within the step of the current iteration. After the second iteration it goes on as expected with 3. If you wnat a different behaviour don't use range instead use a while loop. If you are using a for loop, you probably shouldn't change the index in multiple places like that.

Can you modify for loops?

You can modify the loop variable in a for loop, the problem is that for loops in Python are not like "old-style" for loops in e.g. Java, but more like "new-style" for-each loops.

Can you change a variable in a while loop?

Unlike if statements, the condition in a while loop must eventually become False. If this doesn't happen, the while loop will keep going forever! The best way to make the condition change from True to False is to use a variable as part of the Boolean expression. We can then change the variable inside the while loop.


1 Answers

Well, [(Item1.a, Item2.a), (Item1.b, Item2.b)] just creates a list of tuples of some values. Already by creating this you loose the connection to ItemX. Your problem is not related to the loop.

Maybe you want

for prop in ('a', 'b'):
    i2prop = getattr(Item2, prop)
    if getattr(Item1, prop) != i2prop:
        setattr(Item1, prop, i2prop)

Or something similar but with passing ItemX to the loop too:

for x, y, prop in ((Item1, Item2, 'a'), (Item1, Item2, 'b')):
    yprop = getattr(y, prop)
    if getattr(x, prop) != yprop:
        setattr(x, prop, yprop)
like image 103
Felix Kling Avatar answered Nov 14 '22 23:11

Felix Kling