-2

I've been using Python fine for a few months, however I became very confused this morning when I read a list question. The answer was talking about "References of lists" when you append a list to another or assign a list to another, and it's confusing me (a lot).

Can someone explain to me how lists / list references work?

Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
Thomas Hobohm
  • 645
  • 4
  • 9

2 Answers2

2

Are you talking about:

>>> a = b = []
>>> a.append(2)
>>> print a
[2]
>>> print b
[2]

The reason this is so is because they both reference the same object. id(a) == id(b) (or a is b), and so whatever is added in one is added in the other.

To fix this, you can make a copy of a, which is not the exact same object of a but it has the same content:

>>> a = []
>>> b = a[:]
>>> a.append(2)
>>> a
[2]
>>> b
[]
TerryA
  • 58,805
  • 11
  • 114
  • 143
-1

You can also print a combined list: Not sure if this helps. I would check out the python wiki since they have a more detailed summary of lists and dicts.

a = []
b = []
a.append(15)
print(a)
#[15]
b.append(16)
print(b)
#[16]
print(a+b)
#[15, 16]
Dissious
  • 1
  • 1