-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?

2

2 Answers 2

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
[]
Sign up to request clarification or add additional context in comments.

Comments

-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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.