0

So I am learning python these days and got stuck on a problem. Here is my code.

a = [1, 2, 3, 4, 5]
b = a
print(a)
print(b)
b.append(8)
print(a)
print(b)

The output is as follows.

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 8]
[1, 2, 3, 4, 5, 8]

Why do both lists get modified even when I call it on only b? When we assign b = a, aren't we making a separate copy of that list?

ashwani
  • 690
  • 3
  • 16
  • 1
    You are using different names for the same list, not different lists. Use `b = list(a)` to copy it. – salezica Jul 10 '16 at 00:27
  • No sir, I don't want to know the procedure to copy, I want to know how the above code works and why both lists get modified? – ashwani Jul 10 '16 at 00:29
  • 6
    @user: You are using different names for the same list. If you call my dog Brutus, and I call him Bristo, you could pull on the tail of Brutus, and Bristo would feel pain. They are the same dog. – zondo Jul 10 '16 at 00:32
  • @zondo If *a* is a function instead of list, it will still work the same way? I mean, b = a will still create a alias of *a* with name *b* right? – ashwani Jul 10 '16 at 00:36
  • 1
    @user: That is correct, although usually, functions are not modified, so it doesn't make a difference. – zondo Jul 10 '16 at 00:48
  • Got it. Thanks for help :) – ashwani Jul 10 '16 at 00:53
  • You may find it helpful to read this article, written by veteran SO member Ned Batchelder: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html). – PM 2Ring Jul 10 '16 at 05:46
  • Also see [Other languages have "variables", Python has "names"](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables). – PM 2Ring Jul 10 '16 at 05:57
  • @PM2Ring Awesome articles! Thanks. – ashwani Jul 10 '16 at 12:12

1 Answers1

2

Because python uses references for arrays, objects, etc. If you want a copy of the array use copy:

import copy
b = copy.copy(a)
2ps
  • 15,099
  • 2
  • 27
  • 47
  • Okay I get this. But where can I find a detailed explanation on this? – ashwani Jul 10 '16 at 00:30
  • 2
    You can check out https://docs.python.org/2/reference/simple_stmts.html#assignment-statements which talks about binding and names and how the python language implements them. – 2ps Jul 10 '16 at 00:38