-4
>>> def double(x):
        x += x
>>> a=[1,2,3,4]
>>> b=a
>>> double(b)
>>> print(a)
[1, 2, 3, 4, 1, 2, 3, 4]
>>> print(b)
[1, 2, 3, 4, 1, 2, 3, 4]
>>> 

Could someone help me understand how the a list got doubled in this process? I understand how b's list doubled but not a

Thank you!

Brian
  • 1,659
  • 12
  • 17
Ephraims
  • 1
  • 2
  • 6
    Please fix your indentation. Your code is impossible to understand run together in one line. It looks like the doubling occurs simply because of `x += x`, that is, "add the list to itself." – Two-Bit Alchemist Jun 21 '16 at 17:33
  • 1
    Incidentally, be careful: `b=a` means b and a are **the same list**. If you add to one, you will add to the other! – Two-Bit Alchemist Jun 21 '16 at 17:33

1 Answers1

0

I think this is what your code looks like:

def double(x):
    x += x

a=[1,2,3,4]
b=a
double(b)
print(a)
print(b)

Output:

[1,2,3,4,1,2,3,4]
[1,2,3,4,1,2,3,4]

And the reason is simply that if you have a list x = [1,2,3] and a list y = [6,7,8], then x + y gives you [1,2,3,6,7,8]. So the line x += x adds the elements of x to the end of itself, doubling it.

The reason that a doubles when b doubles is because python lists are mutable. You can find out more here: https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/

johmsp
  • 296
  • 1
  • 8