To make my program more beautiful instead of ugly, I am trying to find a more pythonic way of adding a single value multiple times to a list. I now use a loop, but I create a variable I do not use.
l = []; n = 5; v = 0.5
for i in xrange(n):
l.append(v)
Any ideas?
The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).
The append() method can only add one item at a time. If you want to add multiple elements at once, you'll want to use the extend() method. The extend method takes a list of items as its argument and then adds each of its items to an existing list as a separate item.
To add v, n times, to l:
l += n * [v]
Try using list.extend
and the multiply operator for lists
l.extend([v] * n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With