-1

I have this two sets of code, i assume both should have equal output but they dont. Can someone tell what is going through both code? Any insight is much appreciated. Set 1

x = [[1],[1],[1],[1],[1]]
for i in x:
    print(i)

x[1][0]=99
print(x[1][0])
for i in x:
    print(i)

The output for set1 is

[1]
[1]
[1]
[1]
[1]
99
[1]
[99]
[1]
[1]
[1]

Set2

y = [1]
x = []

for i in range(5):
    x.append(y)
for i in x:
    print(i)

x[1][0]=99
print(x[1][0])
for i in x:
    print(i)

The output for set2 is

[1]
[1]
[1]
[1]
[1]
99
[99]
[99]
[99]
[99]
[99]
Benn ICT
  • 7
  • 1
  • Welcome to Stack Overflow! Please read about [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python-Tutor](http://www.pythontutor.com/visualize.html#mode=edit) which helps to visualize the execution of the code step-by-step. – Tomerikoo Jan 20 '21 at 16:17
  • 1
    `x.append(y)` **keeps appending the same list**. You need to explicitly *copy* the object if you want a copy – juanpa.arrivillaga Jan 20 '21 at 16:19
  • 1
    Probably would be helpful to read: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Jan 20 '21 at 16:22

3 Answers3

0

In the second set, when you do x.append(y) you append a reference of y to x. Thus all changes to the original or any reference of it will be applied to all references.

This is why when you assign a different value at x[1][0]=99 all of the y references get change.

You can read more at: https://www.geeksforgeeks.org/pass-by-reference-vs-value-in-python/

David
  • 8,113
  • 2
  • 17
  • 36
0

You need to understand references in python.

y = [1]
x = []

for i in range(5):
    x.append(y)

This part of your code will fill the list x with references to the y variable, you could imagine it being

>>> x
>>> [y, y, y, y, y]

So further in your code, when you do

x[1][0]=99

You are indeed editing the y variable! So now:

>>> y
>>> [99]

>>> x
# As stated before, it's like [y, y, y, y, y]
>>> [99, 99, 99, 99, 99]

Here's why your code isn't working.

Gugu72
  • 2,052
  • 13
  • 35
0

Because it's by reference. In the second set you are essentially changing y. So all values in x changes.

anik jha
  • 139
  • 1
  • 9