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.
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.
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.
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).
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.
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])
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With