Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list in Python with multiple copies of a given object in a single line

Tags:

python

list

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!

like image 309
Deniz Avatar asked May 07 '10 03:05

Deniz


People also ask

How do you append multiple items to a list in Python in one line?

You can use the sequence method list. extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list.

How do you repeat a list multiple times in Python?

Using the * Operator 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).


2 Answers

You can use the * operator :

L = ["a"] * 10 L = [0] * 10 L = [["x", "y"]] * 10 

Be careful this create N copies of the same item, meaning that in the third case you create a list containing N references to the ["x", "y"] list ; changing L[0][0] for example will modify all other copies as well:

>>> L = [["x", "y"]] * 3 >>> L [['x', 'y'], ['x', 'y'], ['x', 'y']] >>> L[0][0] = "z" [['z', 'y'], ['z', 'y'], ['z', 'y']] 

In this case you might want to use a list comprehension:

L = [["x", "y"] for i in range(10)] 
like image 96
Luper Rouch Avatar answered Sep 20 '22 13:09

Luper Rouch


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

like image 39
Amber Avatar answered Sep 18 '22 13:09

Amber