-1

I have a list-A and I want to create another list-B which contains N copies of list-A

I tried below

list_b = [list_a for _ in range(n)]
#creates copies of the list

from itertools import repeat
list_b = [list_a for _ in repeat(None,n)]
#creates copies of the list

Is there any way to do this without creating a copy of list_a ?

Maunish Dave
  • 359
  • 4
  • 9
  • 2
    `[list_a] * n`? – hnefatl May 25 '20 at 14:59
  • 1
    Dupe of [Create list of single item repeated N times](https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times), if you make the jump to the "single element" being a list and don't mind having references instead of copied values. – hnefatl May 25 '20 at 15:00
  • 2
    What do you mean by "copy"? The first example certainly doesn't make a copy of the list – roganjosh May 25 '20 at 15:00
  • 1
    Your current code creates no copies of `list_a` but builds a new list with a number of *references* to the original list. Just append an element to `list_a` and look at `list_b`... BTW the pythonic way would be `list_b = [list_a] * n`. – Serge Ballesta May 25 '20 at 15:03
  • 1
    Guys, what are you even answering here? They are _not copies_. The list in the first example contains references to the same object in memory. It's not copied. – roganjosh May 25 '20 at 15:03

1 Answers1

1

easy peasy, thank you python

newList = [list_a]  * n

but please note that this copies the reference of original list n times and not copy the elements of the list

ashish singh
  • 6,526
  • 2
  • 15
  • 35