Creating Lists of Repeated Items Efficiently
In Python, creating lists with repeated elements is a common task. One method is to use a list comprehension, e.g., [e for number in range(n)]. However, this approach can be inefficient, especially for large lists.
Alternative Approaches
An alternative is to use Python's built-in repeat method from the itertools module:
itertools.repeat(e, n)
This creates an object that generates repeated values of e on-demand. To obtain a list, simply convert it:
list(itertools.repeat(e, n))
Performance Considerations
While repeat may initially appear faster than the list multiplication method ([e] * n), it creates an object rather than a concrete list. To create the list, it needs to be converted.
[e] * n
This approach directly creates a list filled with n copies of e.
Performance Testing
Performance testing reveals that for large lists, list multiplication is significantly faster:
## repeat() timeit.timeit('itertools.repeat("foo", 1000000)', number=1000) 0.4600000247131665 ## [e] * n timeit.timeit('["foo"] * 1000000', number=1000) 0.19000002993464403
Conclusion
For creating large lists of repeated items, multiplying a single-item list ([e] * n) is the optimal choice due to its superior performance.
The above is the detailed content of What's the Most Efficient Way to Create Large Lists of Repeated Items in Python?. For more information, please follow other related articles on the PHP Chinese website!