Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'm just stumped on how to make the lists separate within the big list.

In short form, this is what I have:

L = [1,2,3,4,5]

If I wanted to to repeat it, say, 3 times so I'd have:

L = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

How do I achieve this? I'm looking for lists within the big list.

like image 334
Matt. Avatar asked Sep 15 '25 03:09

Matt.


1 Answers

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 _ in range(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 :).

like image 153
TerryA Avatar answered Sep 16 '25 18:09

TerryA