Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating elements of a list n times

Tags:

python

How do I repeat each element of a list n times and form a new list? For example:

x = [1,2,3,4] n = 3  x1 = [1,1,1,2,2,2,3,3,3,4,4,4] 

x * n doesn't work

for i in x[i]:     x1 = n * x[i] 

There must be a simple and smart way.

like image 859
user3720101 Avatar asked Jun 14 '14 23:06

user3720101


People also ask

How do you repeat a list in a loop Python?

To repeat each element k times in a list, We will first create an empty list named newList . After that, we will traverse each element of the input list. During traversal, we will add each element of the existing list to the newly created list k times using a for loop, range() method, and the append() method.

How do I make a list of the same values?

Creating a list of same values by List Comprehension with range() This is an another way to create a list of same value using range() i.e. In this list comprehension, for loop will iterate over the range object 20 times and in each iteration it will add 'Hi' in the list. So, list will coatain 20 'Hi' elements i.e.

How do you replicate a list?

The replication of list of a list can be created by using rep function. For example, if we have a list called x and we want to create five times replicated list of this list then we can use the code rep(list(x),5).

What is element repeat?

Repetition is simply repeating a single element many times in a design. For example, you could draw a line horizontally and then draw several others next to it.


2 Answers

The ideal way is probably numpy.repeat:

In [16]:  x1=[1,2,3,4] In [17]:  np.repeat(x1,3) Out[17]: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]) 
like image 117
CT Zhu Avatar answered Oct 13 '22 06:10

CT Zhu


In case you really want result as list, and generator is not sufficient:

import itertools lst = range(1,5) list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))  Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] 
like image 26
m.wasowski Avatar answered Oct 13 '22 06:10

m.wasowski