Home >Backend Development >Python Tutorial >How to Repeat List Elements Multiple Times in Python?
Repeating List Elements Multiply Times
In Python, you may encounter a task where you need to replicate each element of a list multiple times. For instance, given the list x = [1, 2, 3, 4] and a multiplication factor n = 3, you aim to produce a new list x1 with each element repeated n times:
x1 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Ineffective Approaches
Attempting to use x * n will not provide the desired result. Likewise, iterating over x and multiplying each element by n using x1 = n * x[i] is inefficient and prone to logical errors.
Elegant Solution
For a clean and efficient solution, consider utilizing the numpy.repeat function. This function is designed to repeat the elements of an array (or list) a specified number of times:
import numpy as np x1 = np.repeat(x, n)
Using the code above with the example list x and multiplication factor n, x1 will be populated with the desired repeated elements:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
The above is the detailed content of How to Repeat List Elements Multiple Times in Python?. For more information, please follow other related articles on the PHP Chinese website!