Had a question regarding appending to python list. See below
arr1 = []
arr2 = [1,2,3,4,5]
# Method 1
arr1.append(arr2)
# Method 2
arr1.append(list(arr2))
What is the difference between the both append methods above? I ran the above snippet in the python and saw the same results for both as arr1 prints [1,2,3,4,5].
Would it differ when you were to pass the list into a function and perform the same operations?
How to determine when to use # Method 1 or # Method 2?
CodePudding user response:
They only reason to use method two is because you want to create a copy of arr2. Changes to the copy would not affect the original.
Python 3.6.8 (default, Feb 14 2019, 22:09:48)
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> arr1 = []
>>> arr2 = [1,2,3,4,5]
>>> arr1.append(list(arr2))
>>> arr1.append(arr2)
>>> arr2[0] = 9
>>> print(arr1)
[[1, 2, 3, 4, 5], [9, 2, 3, 4, 5]]