Repeat A List Within A List X Number Of Times
I'm working on a project and I need to repeat a list within a list a certain number of times. Obviously, L.append(L) just adds the elements again without creating separate lists. I
Solution 1:
No need for any functions:
>>> L = [1,2,3,4,5]
>>> [L]*3[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
However, you should note that if you change one value in any of the lists, all the others will change because they reference the same object.
>>>mylist = [L]*3>>>mylist[0][0] = 6>>>print mylist
[[6, 2, 3, 4, 5], [6, 2, 3, 4, 5], [6, 2, 3, 4, 5]]
>>>print L
[6, 2, 3, 4, 5]
To avoid this:
>>>L = [1,2,3,4,5]>>>mylist = [L[:] for _ inrange(3)]>>>mylist[0][0] = 6>>>print L
[1, 2, 3, 4, 5]
>>>print mylist
[[6, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
Notice how L
didn't change, and only the first list in mylist
changed.
Thanks everyone in the comments for helping :).
Post a Comment for "Repeat A List Within A List X Number Of Times"