Creating a list in Python with multiple copies of a given object in a single line
list, python
Solution
`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.)
Problem
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!