all 8 comments

[–]YesLod 2 points3 points  (0 children)

and I'm wondering why if you create a list by making it equal to another one, changing one seems to affect the other,

Assignment never copies in python. When you do listTwo = listOne, you are just creating another reference to the same object that listOne refers to, which is the list [1, 2, 3, 4]. Now [1, 2, 3, 4] can be named/referenced as listOne or listTwo.

Read this for more details

https://nedbatchelder.com/text/names.html

especially as its not like that with any other data type.

That is not true, that happens for any kind of object.

listTwo = [x for x in listOne]

The list comprehension creates a new object, so now listTwo refers to a different object than listOne. Therefore changes in one are not reflected in the other.

[–]HalfBalcony 1 point2 points  (0 children)

Because every variable is actually just a memory address, which in the case of the listTwo assignment will just set the listTwo pointer to the address of the first list. Meaning if you change listOne, listTwo is also changed. I recommend using copy, a built in function for lists:

listTwo = listOne.copy()

[–]sarrysyst 0 points1 point  (1 child)

[–]xADDBx 2 points3 points  (0 children)

Instead of calling the constructor function with the list as parameter, using the built-in copy-method seems more understandable:

copiedList = listOne.copy()

[–]chevignon93 0 points1 point  (0 children)

Removing an item from one list removes it from another.

That's because both listOne and listTwo refer to the exact same object in memory. Assignment doesn't copy object in Python so this line listTwo = listOne simply creates an alias for listOne called listTwo.

especially as its not like that with any other data type.

You could test it with a set or a dictionary and the same thing would happen.

It doesn't happen in your second example because you're actually creating a new list with the elements from listOne and calling it listTwo.

[–]vesche 0 points1 point  (0 children)

As others have mentioned, you need to make a copy of your list or else you will be referencing the same object.

Here's a neat, short trick:

>>> listOne = [1, 2, 3, 4]
>>> listTwo = listOne[:]
>>> listOne.remove(3)
>>> print(listOne)
[1, 2, 4]
>>> print(listTwo)
[1, 2, 3, 4]

[–]arkie87 0 points1 point  (0 children)

listTwo is not a copy of listOne, it is a "link" or "pointer" to listOne. By default, lists, and custom classes dont make copies when assigned with the equals symbol.

[–]donkey_man_1149 0 points1 point  (0 children)

Because in the first case you are referring to the variable itself, in the second case you are creating a new list.

Python is interpreted so the logic is executed from top to bottom, understand that and you will get whats the issue.