I am having some trouble with Python, I know in other languages everything you do is pretty straight forward and very logical. However, in Python, appending
a list
with data
to a new list
simply keeps a reference or pointer, and as a result, any changes made to the original list are apparent in the new list.
I have heard about copy.copy(list[:])
, but I am not 100% percent sure this would work well.
list_1 = [1, 2, 3]
new_list = []
new_list.append(list_1[:])
However, if you modify list_1, you also modify new_list, since they point to the same list.
>>> list_1.append(4)
>>> print list_1
[1, 2, 3, 4]
>>> print new_list
[1, 2, 3, 4]
All of this is really annoying to me. If anyone knows a better way, please tell me.
I want to be able to make changes to the list_1 and continue to append
to the new_list, so that I populate the new_list like this:
new_list
[0] >>>
[1, 2, 3, 4]
[1] >>>
[5, 6, 7, 8]
And sometimes the first list can also be larger than what claimed by this example.
Made a test run now:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> list_1 = [1,2,3]
>>> new_list = []
>>> new_list.append(list_1[:])
>>> print new_list
SyntaxError: Missing parentheses in call to 'print'
>>> print(new_list)
[[1, 2, 3]]
>>> list_1.append(4)
>>> print(new_list)
[[1, 2, 3]]
>>> print(new_list)
[[1, 2, 3]]
>>> print(list_1)
[1, 2, 3, 4]
Strange. Strange. Strange.