Appending a value to a list inside a list

Question:

A simple question regarding the appending rule of list.

So the code is

list = [1,2,3,4]
for x in [list] #Yes a list in a list:
    x.append(2)

print(x)
print(list)

The result of the two print is both [1,2,3,4,2]. I can see why print(x) outputs 1,2,3,4,2 but I didnt update the list yet but somehow the list is also updated.

Is there a hidden rule behind this? or is it just a default setting I need to memorize.

Thanks

Two prints have the same output and I wanna know why

Asked By: ceramics.2

||

Answers:

Lists in python are by reference, not by value.
inner list in [list] is referring to the same list as outside list
Therefore, the append you do is visible in both references (they are the same list).

I’ve made a simpler example that illustrates the same point:

a = [1, 2, 3]
b = [a]
b[0].append(4)
print(a)
>>> [1, 2, 3, 4]
Answered By: Sebastian

Here is a similar code to yours, I broken down to explain it better:

sublist = [1,2,3,4]

sublist is a simple 1d array.

li = [sublist] 

li is a list containing sublist, effectivly a 2d array.

for x in li:

If you iterate over li, x is each element of li, so first a final iteration, x will be the list [1,2,3,4].

x.append(2)

Then you append 2 to x so you are effectivly appending to sublist.

The complete code looks like this:

sublist = [1,2,3,4]
li = [sublist] 
print(li) # => [[1, 2, 3, 4]]
for x in li:
    print(x) # => [1, 2, 3, 4]
    x.append(2) # appending 2 to x (i.e [1, 2, 3, 4] <= 2) that is contained in li
print(x) # => [1, 2, 3, 4, 2]
print(li) # => [[1, 2, 3, 4, 2]]
Answered By: Olivier Neve
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.