In this article, we are going to learn how to expand the list by replicating the element K times. We'll two different ways to solve the problem.
Follow the below steps to solve the problem.
- Initialize the list, K, and an empty list.
- 3Iterate over the list and add current element K times using replication operator.
- Print the result.
Example
Let's see the code.
# initializing the list numbers = [1, 2, 3] K = 5 # empty list result = [] # expanding the list for i in numbers: result += [i] * K # printing the list print(result)
If you run the above code, then you will get the following result.
Output
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Follow the below steps to solve the problem.
- Initialize the list and K.
- Iterate over the list and add current element K times using an inner loop.
- Print the result.
Example
Let's see the code.
# initializing the list numbers = [1, 2, 3] K = 5 # expanding the list result = [i for i in numbers for j in range(K)] # printing the list print(result)
If you run the above code, then you will get the following result.
Output
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Conclusion
If you have any queries in the article, mention them in the comment section.