Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of single item repeated N times

I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated n times (where n = length of the list).

How do I create the lists, without using a list comprehension [e for number in xrange(n)] for each list?

like image 344
chimeracoder Avatar asked Aug 11 '10 14:08

chimeracoder


People also ask

How do you repeat a list and times?

To repeat the elements of the list n times, we will first copy the existing list into a temporary list. After that, we will add the elements of the temporary list to the original list n times using a for loop, range() method, and the append() method.

How do you make a list with N elements in Python?

To create a list of n placeholder elements, multiply the list of a single placeholder element with n . For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None . You can then overwrite some elements with index assignments.


1 Answers

You can also write:

[e] * n 

You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.

Performance testing

At first glance it seems that repeat is the fastest way to create a list with n identical elements:

>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000) 0.37095273281943264 >>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000) 0.5577236771712819 

But wait - it's not a fair test...

>>> itertools.repeat(0, 10) repeat(0, 10)  # Not a list!!! 

The function itertools.repeat doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:

>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000) 1.7508119747063233 

So if you want a list, use [e] * n. If you want to generate the elements lazily, use repeat.

like image 65
Mark Byers Avatar answered Sep 22 '22 06:09

Mark Byers