0

I stumbled upon this just now, and i have no idea if this is intended behaviour or a bug. consider the following code:

global a,b;
a=[0,1,2];
b=a;
print("before:",a,b);
def c():
    global a,b;
    for i in range(3):
        a.append(10+i);
c();
print("after:",a,b);

what should happen (at least according to what seems logical to me) is that python only touches the variable a during the appending process. instead, it decides to the very same thing to b even though i've never told it to touch b inside the appending loop. is there some kind of hidden relation to a and b i've unknowingly set by making them global, or is this a bug?

sidenotes: replacing global a,b; with just global a; inside c() gives me the same output.

i've tried doing the same with the + operator on strings and integers, this seems to be exclusive to the .append function, just a guess though.

I'm running this on Python 3.5.0 x64 on Windows 10

peak
  • 105,803
  • 17
  • 152
  • 177
jeer1011
  • 9
  • 2
  • 3
    Briefly: `b=a` makes them both point to the same object. – TigerhawkT3 Jan 04 '16 at 00:28
  • 3
    Also, Python does not require a semicolon to end each statement. Their use is discouraged. – TigerhawkT3 Jan 04 '16 at 00:28
  • 1
    Additionally, it's generally a safer bet to assume that there is a flaw in your program or in your understanding of Python (generic "your," not you in particular) rather than that there is a huge bug in a language that's been used by many developers for decades. – TigerhawkT3 Jan 04 '16 at 00:31
  • @TigerhawkT3 I see, it's confusing as whenever python decides to use pointers and direct references, what i want to is copy a into b and thus make them have no relation to eachother. the duplicate-linked question above has some confusing answers, mind giving me a short summary of how i would do that? – jeer1011 Jan 04 '16 at 00:33
  • There's no deciding going on; Python always passes by reference. As to your followup question, have you tried Googling something like "how do i copy a list in python"? – TigerhawkT3 Jan 04 '16 at 00:37
  • @TigerhawkT3 I understand, thanks! – jeer1011 Jan 04 '16 at 00:43
  • 1
    i know this wasn't asked but if you need to copy the list you can do so by slicing use `b = a[:]` – danidee Jan 04 '16 at 03:29
  • Do not use `global` at all. You do not need it. – pepr Jan 04 '16 at 10:49
  • @pepr i do though, as i'm doing threading and it's a lot simpler than using queing. – jeer1011 Jan 04 '16 at 20:07
  • OK. Anyway, the `global` should be used only inside the `c` function. You can also add `print(id(a), id(b))` to make it clear that `a` and `b` point to the identical objects. Follow the daidee's comment to make a copy of the list. – pepr Jan 05 '16 at 14:39
  • @pepr yeah, already have b=list(a); – jeer1011 Jan 05 '16 at 17:09

0 Answers0