-1

Can someone explain to me why the output would be:

[[8, 0]]
[[8, 0], [8, 0], [8, 0]]

This is the function that is confusing me

x = [[0,0]]
y = x * 3
i = 10


for inner in y:
    inner[0] = i
    i -= 1
print(x)
print(y)
  • On `line 5`, you are replacing first value of list `x` from `i` which is `10`. When the loop ends the value of `i` is `8` which is again has been assigned to `0th` index of `x`. That's why you get, `[[8, 0]]` for `x` and `[[8, 0], [8, 0], [8, 0]]` for `y`. Hope it helps. – the.salman.a Mar 20 '18 at 05:42
  • See here: https://stackoverflow.com/questions/6688223/python-list-multiplication-3-makes-3-lists-which-mirror-each-other-when – kaveh Mar 20 '18 at 05:42
  • Each element of `y` is pointing to the same list and when you change one, you see the update in all the items referencing the original list. – kaveh Mar 20 '18 at 05:46

2 Answers2

0

In python, with new_list = my_list, you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment. Check this question for reference.

In your code, the result of y = x*3 is that you have three elements in y referring to the same list, which is x. Therefore, when inner[0] = i is executed, actually the list that all the three elements in y are referring to is changed. For example, when the for loop is executed for the first time, print(y) gives the result [[10, 0], [10, 0], [10, 0]]

llxxee
  • 59
  • 1
  • 6
0

Perhaps it will be easier to see what is happening with the 1st element of each nested list if you print out what's going on. On the first pass the the 1st element of each nested list inner[0] is set to 10. Before the loop ends you're subtracting 1. When the loop ends you end up with 8. The 2nd list still refers to the 1st list which why both lists get changed. An excellent debugging technique is to print stuff out one item at a time if your program doesn't work or if you don't understand what's going on.

You didn't say if you're using Python 2 or 3 but since you're print statements have parentheses I'll just assume it's Python 3.

#!python3

x = [[0,1]]
y = x * 3 # 'y' is now equal to [[0, 1], [0, 1], [0, 1]]
i = 10

# 'enumerate' is the python prefered method of a counter, it's zero indexed
for j, inner in enumerate(y):
    inner[0] = i
    print(inner[0], 'pass:', j)
    i -= 1
    print(inner[0], 'pass:', j)

print()

print("After running 'x' is:", x)
print()
print("After running 'y' is:", y)
Michael Swartz
  • 858
  • 2
  • 15
  • 27