0

In messing around with some old code I posted awhile back, I came across something odd. Rather than using i += prim in my code, I've got this ugly i = i + prim. Not a big deal, I'll just changed it while changing other things. But what's this? My code is broken!

def gen_all_pyth_trips(limit):
    for prim in gen_prim_pyth_trips(limit):
        i = prim
        for _ in range(limit//prim[2]):
            yield i
            # i = i + prim
            i += prim

Context

So I'm pretty sure this has something to do with the fact that the first one is creating a new object and telling i to reference it while the second one is changing the object that i is referencing (thus changing prim and all the yielded arrays) but the reasons aren't all that obvious (to me at least).

If someone could point me to some documentation and/or explain what exactly is going on here, I'd be much obliged.

Community
  • 1
  • 1
Kyle G
  • 1,017
  • 11
  • 18
  • 3
    What exactly is the error you're receiving? – furkle Oct 29 '14 at 01:59
  • 2
    Why do you have a `%` in `% i = i + prim`? – David Robinson Oct 29 '14 at 02:02
  • Not an error persay but as an example, using `i += prim` with `list(gen_all_pyth_trips(10))` returns `[array([12, 16, 20]), array([12, 16, 20])]` instead of `[array([3, 4, 5]), array([6, 8, 10])]` – Kyle G Oct 29 '14 at 02:05
  • 2
    Assuming i is mutable (e.g. a list), += will modify the object, while `i = i + prim` will assign a new object to i: http://stackoverflow.com/questions/9766387/different-behaviour-for-list-iadd-and-list-add – happydave Oct 29 '14 at 02:11
  • Pretty much what I was thinking, just couldn't find info on it. Thanks @happydave – Kyle G Oct 29 '14 at 02:17
  • 1
    This is what you're looking for. It describes the "in place" operators `+=` versus `+`, etc... https://docs.python.org/3/library/operator.html#inplace-operators – Dunes Oct 29 '14 at 03:19

0 Answers0