Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append the same value multiple times to a list [duplicate]

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?

like image 659
Bsje Avatar asked Dec 06 '13 14:12

Bsje


People also ask

How do you repeat a value in a list Python?

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).

Can you append multiple elements to a list?

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.


2 Answers

To add v, n times, to l:

l += n * [v]
like image 133
Boo Avatar answered Oct 21 '22 06:10

Boo


Try using list.extend and the multiply operator for lists

l.extend([v] * n)
like image 25
Nils Werner Avatar answered Oct 21 '22 04:10

Nils Werner