[newbie] copying identical list for a function argument

Tim Chase python.list at tim.thechases.com
Mon Feb 3 16:51:23 EST 2014


On 2014-02-03 13:36, Jean Dupont wrote:
> I have a list like this:
> [1,2,3]
> 
> The argument of my function should be a repeated version e.g.
> [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of
> times repeated also)
> 
> what is the prefered method to realize this in Python?
> 
> any help would be really appreciated

It depends on whether you want the contained list to be the *same*
list or *copies* of that list.  You can do either of the following:

  lst = [1,2,3]
  dupes1 = [lst[:] for _ in range(5)]
  dupes2 = [lst for _ in range(5)]
  dupes3 = [lst] * 5

The dupes2 and dupes3 should be the same (the latter is a simpler
syntax for it): each contains the same list multiple times.  To see
this, do

  lst.append(4)

and then inspect dupes1 compared to dupes2/dupes3.

-tkc





More information about the Python-list mailing list