Creating a list in Python with multiple copies of a given object in a single line

Question:

Suppose I have a given Object (a string “a”, a number – let’s say 0, or a list ['x','y'] )

I’d like to create list containing many copies of this object, but without using a for loop:

L = ["a", "a", ... , "a", "a"]

or

L = [0, 0, ... , 0, 0]

or

L = [['x','y'],['x','y'], ... ,['x','y'],['x','y']]

I’m especially interested in the third case.
Thanks!

Asked By: Deniz

||

Answers:

itertools.repeat() is your friend.

L = list(itertools.repeat("a", 20)) # 20 copies of "a"

L = list(itertools.repeat(10, 20))  # 20 copies of 10

L = list(itertools.repeat(['x','y'], 20)) # 20 copies of ['x','y']

Note that in the third case, since lists are referred to by reference, changing one instance of [‘x’,’y’] in the list will change all of them, since they all refer to the same list.

To avoid referencing the same item, you can use a comprehension instead to create new objects for each list element:

L = [['x','y'] for i in range(20)]

(For Python 2.x, use xrange() instead of range() for performance.)

Answered By: Amber

You can use the * operator :

L = ["a"] * 10
L = [0] * 10
L = [["x", "y"]] * 10

Be careful this create N copies of the same item, meaning that in the third case you create a list containing N references to the ["x", "y"] list ; changing L[0][0] for example will modify all other copies as well:

>>> L = [["x", "y"]] * 3
>>> L
[['x', 'y'], ['x', 'y'], ['x', 'y']]
>>> L[0][0] = "z"
[['z', 'y'], ['z', 'y'], ['z', 'y']]

In this case you might want to use a list comprehension:

L = [["x", "y"] for i in range(10)]
Answered By: Luper Rouch

You could do something like

x = <your object>
n = <times to be repeated>
L = [x for i in xrange(n)]

Substitute range(n) for Python 3.

Answered By: John Flatness

If you want unique instances and like to golf, this is (slightly) shorter:

L = [['x', 'y'] for _ in []*10]

The crazy thing is that it’s also (appreciably) faster:

>>> timeit("[['x', 'y'] for _ in [0]*1000]", number=100000)   
8.252447253966238                                             
>>> timeit("[['x', 'y'] for _ in range(1000)]", number=100000)
9.461477918957826
Answered By: krs013

I hope this helps somebody. I wanted to add multiple copies of a dict into a list and came up with:

>>> myDict = { "k1" : "v1" }
>>> myNuList = [ myDict.copy() for i in range(6) ]
>>> myNuList
[{'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}]
>>> myNuList[1]['k1'] = 'v4'
>>> myNuList
[{'k1': 'v3'}, {'k1': 'v4'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}]

I found that:

>>> myNuList = [ myDict for i in range(6) ]

Did not make fresh copies of the dict.

Answered By: Ed McGuigan

In case you want to create a list with repeating elements inserted among others, tuple unpacking comes in handy:

l = ['a', *(5*['b']), 'c']
l
Out[100]: ['a', 'b', 'b', 'b', 'b', 'b', 'c']

[the docs]

Answered By: FObersteiner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.