This seems like something Python would have a shortcut for. I want to append an item to a list N times, effectively doing this:
l = []
x = 0
for i in range(100):
l.append(x)
It would seem to me that there should be an "optimized" method for that, something like:
l.append_multiple(x, 100)
Is there?
l = []
x = 0
l.extend([x]*100)
Use extend to add a list comprehension to the end.
l.extend([x for i in range(100)])
See the Python docs for more information.
Itertools repeat combined with list extend.
from itertools import repeat
l = []
l.extend(repeat(x, 100))
I had to go another route for an assignment but this is what I ended up with.
my_array += ([x] * repeated_times)
You could do this with a list comprehension
l = [x for i in range(10)];
Source: Stackoverflow.com