Home >Backend Development >Python Tutorial >How to Repeat List Elements Multiple Times in Python?

How to Repeat List Elements Multiple Times in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 14:02:02856browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn