List replication operator

bartc bc at freeuk.com
Fri May 25 08:44:21 EDT 2018


On 25/05/2018 13:36, bartc wrote:

> Of course you have to implement dupllist(), but you'd have to implement 
> ** too, and that is harder. For this specific example, it can just be:
> 
> def dupllist(x,n):
>      return [x[0].copy() for _ in range(n)]
> 

On 25/05/2018 03:25, Steven D'Aprano wrote:
 > You might be right: on further thought, I think I want deep copies, not
 > shallow.

And my solution just becomes:

import copy

def dupllist(x,n):
     return [copy.deepcopy(x[0]) for i in range(n)]

(It needs to iterate repeatedly over the elements of x for a general 
list. Replacing [0] by [i%len(x)] might just do it.)


-- 
bartc



More information about the Python-list mailing list