4

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.

halo09876
  • 2,725
  • 12
  • 51
  • 71
  • Try [a]*5....... – Paul Panzer Mar 08 '17 at 05:56
  • 1
    Do you want the sublists to be independent, or do you want them all to be references to the one `a` list? IOW, if you do `output[1][1] = '5'`, do you want `output` to become `[['1', '5', '3', '4'], ['1', '5', '3', '4'], ['1', '5', '3', '4'], ...]` ? – PM 2Ring Mar 08 '17 at 05:59

6 Answers6

10

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)]
5

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']]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

You're very close. While a * 2 may give you [1, 2, 3, 4, 1, 2, 3, 4], there is a way to use that same operator to get the result you want. It's just repeating the contents, so try [a] * 2.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
1

Use list comprehension

>>> b = [a for i in range(3)]
>>> b
[['1', '2', '3', '4'], ['1', '2', '3', '4'], ['1', '2', '3', '4']]

You can do various such operations over lists. Check this link here

Venkat Ramana
  • 508
  • 1
  • 6
  • 16
1

As per my understanding, you need to replicate list without using same reference to perform some operation in future.

you will try this piece of code to generate a list containing n times replicated list

import copy
a = [1,2,3,4]
n = 1000
def replicateMaster(n, a):
    output= []
    while n != 0:
        n -= 1
        output.append(copy.deepcopy(a))
    return output

Or simply use this shorthand:

import copy
a = [1,2,3,4]
n = 1000
output = [copy.deepcopy(a) for i in range(n)]

hopefully this code is solve your problem

Rahul Gupta
  • 716
  • 7
  • 14
-1

try

output = print([a]*no_of_count)
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
ihsahs
  • 58
  • 9