Python Forum
why does the list of list replicate this way? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: why does the list of list replicate this way? (/thread-6616.html)



why does the list of list replicate this way? - hshivaraj - Nov-30-2017



a = [[]] * 10

a
[[], [], [], [], [], [], [], [], [], []]

a[0].append((1,2))

a
[[(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)], [(1, 2)]]
Why does it replicate the values across the entire list? Bizarre Huh


RE: why does the list of list replicate this way? - Windspar - Nov-30-2017

Because list are reference. [[]] * 10 makes 10 reference copies.
a = [[] for x in range(10)]



RE: why does the list of list replicate this way? - hshivaraj - Dec-01-2017

Thanks very much windspar.
That was as simple as that :)