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)
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)
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]]
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)