Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add, say, n entries of x to a list in one shot?

Tags:

python

list

For instance, say list L = [0,1,2,3] and I want to add 10 elements of 4:

L=[0,1,2,3,4,4,4,4,4,4,4,4,4,4] 

without needing to use a loop or anything

like image 854
WhatsInAName Avatar asked Jan 04 '12 03:01

WhatsInAName


2 Answers

This is pretty simple thanks to the fact you can add and/or multiply lists:

L += [4] * 10

Here is the proof:

>>> L = [0,1,2,3]
>>> L += [4] * 10
>>> L
[0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
like image 184
Tadeck Avatar answered Nov 14 '22 23:11

Tadeck


L.extend([4] * 10)

L.extend([some_mutable_object for x in range(10)])
like image 33
Ignacio Vazquez-Abrams Avatar answered Nov 14 '22 23:11

Ignacio Vazquez-Abrams