I want to replicate a list more than 1000 times and then append to a larger list.
For instance:
a = ['1','2','3','4]
When replicating this list and then nesting it a hundred times:
output = [['1','2','3','4],['1','2','3','4],['1','2','3','4],['1','2','3','4],['1','2','3','4].....]
So far I've only come across a*2, which is not want I want.
You can easily replicate the list by the following.
a = ['1','2','3','4']
output = [a]*1000
The above will create reference. If you need separate copy then do the following.
a = ['1','2','3','4']
output = [a[:] for i in range(1000)]
In that case you should use [a]*2
. But note that the *
operator will create multiply references to your main object, since it's a mutable object. Instead as a more pythonic way you can use itertools.repeat()
which will give you separate copies of your main object:
In [2]: from itertools import repeat
In [5]: a = ['1','2','3','4']
In [6]: list(repeat(a, 4))
Out[6]:
[['1', '2', '3', '4'],
['1', '2', '3', '4'],
['1', '2', '3', '4'],
['1', '2', '3', '4']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With