how to repeat elements of nested list?

I have a list of lists as follows:

original = [['best', 'movie', 'ever', '!'],
            ['i', 'love', 'this', 'actor', '!'],
            ['season','2']] 

I want to create a new list, where each element in the original list repeated 3 times. The desired result is:

new_list = [['best', 'movie', 'ever', '!'],
            ['best', 'movie', 'ever', '!'],
            ['best', 'movie', 'ever', '!'],
            ['i', 'love', 'this', 'actor', '!'],
            ['i', 'love', 'this', 'actor', '!'],
            ['i', 'love', 'this', 'actor', '!'],
            ['season','2'],
            ['season','2'],
            ['season','2']] 

I tried this:

new_list = [i*3 for i in original]

It returns:

[['best','movie','ever','!','best','movie','ever','!','best','movie','ever','!'],
 ['i','love','this','actor','!','i','love','this','actor','!','i','love','this','actor','!'],
 ['season', '2', 'season', '2', 'season', '2']]

How I can correct the code to get the desired output?

Answer

Just use:

[x for x in original for _ in range(3)]

Although, you may need to use:

[x.copy() for x in original for _ in range(3)]

Leave a Reply

Your email address will not be published. Required fields are marked *