Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find replicated list by replicating each element n times
Suppose we have a list of n elements; we have to repeat each element in the list n number of times.
So, if the input is like nums = [1,5,8,3], then the output will be [1, 1, 1, 1, 5, 5, 5, 5, 8, 8, 8, 8, 3, 3, 3, 3]
To solve this, we will follow these steps −
- n := size of nums
- ret := a new list
- for each num in nums, do
- ret := ret concatenate a list with n number of nums
- return ret
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
n = len(nums)
ret = []
for num in nums:
ret += [num] * n
return ret
nums = [1, 5, 8, 3]
print(solve(nums))
The output of the above code is ?
[1, 1, 1, 1, 5, 5, 5, 5, 8, 8, 8, 8, 3, 3, 3, 3]
Using List Comprehension
We can also solve this problem using list comprehension for a more concise solution ?
def solve_compact(nums):
n = len(nums)
return [num for num in nums for _ in range(n)]
nums = [1, 5, 8, 3]
result = solve_compact(nums)
print(result)
[1, 1, 1, 1, 5, 5, 5, 5, 8, 8, 8, 8, 3, 3, 3, 3]
Using itertools.repeat()
Another approach uses itertools.repeat() with itertools.chain() ?
import itertools
def solve_itertools(nums):
n = len(nums)
return list(itertools.chain.from_iterable(itertools.repeat(num, n) for num in nums))
nums = [1, 5, 8, 3]
result = solve_itertools(nums)
print(result)
[1, 1, 1, 1, 5, 5, 5, 5, 8, 8, 8, 8, 3, 3, 3, 3]
Comparison
| Method | Readability | Performance |
|---|---|---|
| Basic Loop | High | Good |
| List Comprehension | Medium | Better |
| itertools | Low | Best |
Conclusion
Use the basic loop approach for clarity and readability. List comprehension offers a more Pythonic solution, while itertools provides the best performance for large datasets.
Advertisements
