Python Forum
What this code will output and why? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: What this code will output and why? (/thread-4612.html)



What this code will output and why? - Valgard - Aug-30-2017

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?


RE: What this code will output and why? - BerlingSwe - Aug-30-2017

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


RE: What this code will output and why? - dwiga - Aug-30-2017

Output:
[['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]



RE: What this code will output and why? - snippsat - Aug-30-2017

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



RE: What this code will output and why? - Valgard - Aug-30-2017

Thank you for detailed answer. I will experiment with this python feature.