1

I have the following:

class Trade:
    def __init__(self):
        entry = [0, 1, 2, 3]
        exit = [1, 2, 3, 4]
        met = [0, 0, 0, 0]
        self.stats = zip(entry, exit, met)



t = Trade()

for entry, exit, met in t.stats:
        met = 1

for entry, exit, met in t.stats:
    print(entry, exit, met)

I am expecting all values of met to be 1. But that is not the case. What is the reason for this, and how can I make it so that the modifications to met are reflected in the instance of Trade class t. Does the for statement produce a copy of t.stats rather than iterating through its original copy?

2 Answers 2

6

When you loop over the values of a list, the values are assigned to local variables. Changing those local variables will not change the original values stored in the list.

Use a enumerate() call to add indexes, then use that index to change the original list:

for i, (entry, exit, met) in enumerate(t.stats):
    t.stats[i] = (entry, exit, 1)
3
  • Oh I see, what is @mgilson 's comment referring to? I cannot modify t.stats?
    – Joshua
    Jan 23, 2013 at 16:22
  • 1
    @Joshua: you can modify t.stats, you cannot modify individual entries in the nested tuples. Replace the tuples wholesale (like I did in my answer).
    – Martijn Pieters
    Jan 23, 2013 at 16:23
  • I usually do something like for i, (entry, exit, _) in enumerate(t.stats):, the _ is kind of a signal that says "no one cares about me outside of this statement".
    – BenDundee
    Jan 23, 2013 at 16:23
2

The following will do it:

t.stats[:] = [(entry, exit, 1) for entry, exit, met in t.stats]

The reason your code doesn't work is that met = 1 simply rebinds met to point elsewhere. This has no effect on t.stats.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.