Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replicate a list a certain number of times [duplicate]

Tags:

python

list

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.

like image 812
song0089 Avatar asked Dec 03 '22 22:12

song0089


2 Answers

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)]
like image 82
Kaushal Kumar Singh Avatar answered Dec 11 '22 16:12

Kaushal Kumar Singh


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']]
like image 31
Mazdak Avatar answered Dec 11 '22 16:12

Mazdak