4

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.

smci
  • 32,567
  • 20
  • 113
  • 146
Matt.
  • 1,306
  • 2
  • 13
  • 20
  • 1
    As a side note, that's not that `L.append(L)` does. Try it out and see; you'll be surprised by what it does (and it's worth understanding). – abarnert Apr 19 '13 at 01:54
  • @abarnert Wow, I never knew about that. Is that just what is executed when an infinite loop is found or something? – TerryA Apr 19 '13 at 02:02
  • It just adds a copy of `L` itself as the last element of `L`. There's nothing necessarily infinite about it… But if you try to, say, flatten it out, or walk it like a tree, _that_ will give you an infinite loop. (If you think about it, printing out a list means walking it like a tree… but Python is smart enough to check for that when printing out a list, so you get `[1, 2, 3, 4, 5, [...]]` instead of an infinite wall of text.) – abarnert Apr 19 '13 at 02:09
  • @Haidro: Anyway, this is really the same as `mylist[0]` and `mylist[1]` being references to the same thing, as you explained in your answer. It's just that `L` and `L[5]` are references to the same thing. – abarnert Apr 19 '13 at 02:10
  • Similar questions: [Circular list iterator in Python](https://stackoverflow.com/questions/23416381/circular-list-iterator-in-python), [Create list of single item repeated N times](https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python), [Repeating elements of a list n times](https://stackoverflow.com/questions/24225072/repeating-elements-of-a-list-n-times), [Best way to extend a list with itself N times](https://stackoverflow.com/questions/46560385/best-way-to-extend-a-list-with-itself-n-times). – Georgy Oct 01 '19 at 20:43

1 Answers1

10

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 :).

TerryA
  • 58,805
  • 11
  • 114
  • 143