Python Forum

Full Version: What this code will output and why?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Today I meet this exercise:

What this code will output and why?

x = [[]]*3
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0]=['d']

print(x)

I expected to see 'd b c', but whet i run this program i was surprised. The output is [['d'], ['a', 'b', 'c'], ['a', 'b', 'c']].
Why is this code works this way?
Brcause you are using a 2 dimensional list. Play around with it for a bit and I'm sure you will understand! :)

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a[0])
print(a[0][1])
Try this code and experiment with it by printing, removing, appending etc
Output:
[['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]
x = [[]]*3 this copy 3 list to  same memory adress.
>>> x = [[]]*3
>>> [id(i) for i in x]
[57560800, 57560800, 57560800]
Do it like this.
>>> x = [[] for i in range(3)]
>>> [id(i) for i in x]
[66352912, 66412416, 65766344]
Then it look like this.
x = [[] for i in range(3)]
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0] = ['d']

print(x)
Output:
[['d'], ['b'], ['c']]
Thank you for detailed answer. I will experiment with this python feature.