0

when I want to copy my list and try to remove an item from one list, it also disappears in the other list. Can you give me a reason? And how do I remove from only one list?

letter_list = ["A","B","C"]
same_letter_list = letter_list

print same_letter_list
print letter_list

same_letter_list.remove("B")

print same_letter_list
print letter_list

My output is:

['A', 'B', 'C']
['A', 'B', 'C']
['A', 'C']
['A', 'C']

I'm new in programming. Thanks for your help!

Kim
  • 57
  • 5
  • `same_letter_list = letter_list` makes `same_letter_list` reference the *same list*. There's only 1 list here, with two names. – Dimitris Fasarakis Hilliard Sep 20 '16 at 18:15
  • 1
    This seems very similar to this other question: http://stackoverflow.com/questions/8744113/python-list-by-value-not-by-reference – Malcolm G Sep 20 '16 at 18:17
  • 1
    If you are new to Python, why are you starting with Python 2? The [Stack Overflow Python community](http://sopython.com) overwhelmingly [recommends](http://sopython.com/wiki/What_tutorial_should_I_read%3F) starting with Python 3, as does [python.org itself](https://wiki.python.org/moin/Python2orPython3). Version 3 is the present and future of the language, while 2 is the past. In learning 2 first, you'll pick up many bad habits that will need to be corrected when you learn 3 (which you'll need to do eventually), so it's much better to start with 3 first, then learn the differences in 2 later. – MattDMo Sep 20 '16 at 18:26
  • Also, please don't tag questions with both `python-2.7` and `python-3.x` unless you are asking about differences between the two versions, or something similar. Just tag what you're *using*, which is clearly Py2 because of the `print` statements. – MattDMo Sep 20 '16 at 18:28

3 Answers3

0

Because same_letter_list and letter_list is the same list. And it reference to the same memory.

If you want to make them separate, make a copy

same_letter_list = letter_list.copy()
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
0

The list is the same. You can slice it to the other variable so that they are different. Like this :

letter_list = ["A","B","C"]
same_letter_list = letter_list[:]

print same_letter_list
print letter_list

same_letter_list.remove("B")

print same_letter_list
print letter_list
acknowledge
  • 434
  • 6
  • 12
0

basically letter_list and same_letter_list are the same address

>>> letter_list = ["A","B","C"]
... same_letter_list = letter_list
... 
>>> id(same_letter_list)
1316298424
>>> id(letter_list)
1316298424

it will give a new address

diff_letter_list = letter_list[:]
id(diff_letter_list)
1307621296
galaxyan
  • 5,944
  • 2
  • 19
  • 43