Open In App

Python | Repeat each element K times in list

Last Updated : 11 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many times we have this particular use case in which we need to repeat each element of the list K times. The problems of making a double clone have been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Let’s discuss certain ways in which this can be performed. 

Approach 1: Using a loop

Here, we are using two Python loops in the first loop we iterate the loop to the length of the list, and in the second loop, we append the element to the list from the first loop.

Approach:

  1. Initialize the list of integers named test_list with values [4, 5, 6].
  2. Print the original list using the print() function. The statement is print(“The original list : ” + str(test_list)).
  3. Declare the magnitude of repetition K to 3.
  4. Create an empty list named res to store the result after adding elements.
  5. Use two nested loops to repeat each element of the test_list K times, and store the result in the res list.
  6. The outer loop iterates through each element of test_list, and the inner loop iterates K times to repeat each element. The statement is for i in test_list: for ele in range(K): res.append(i).
  7. Print the final result using the print() function. The statement is print(“The list after adding elements : ” + str(res)).

Python3




# initializing list of lists
test_list = [4, 5, 6]
 
# printing original list
print("The original list : " + str(test_list))
 
# declaring magnitude of repetition
K = 3
 
# using list comprehension
# repeat elements K times
res = []
for i in test_list:
    for ele in range(K):
        res.append(i)
 
# printing result
print("The list after adding elements : " + str(res))


Output :

The original list : [4, 5, 6]
The list after adding elements :  [4, 4, 4, 5, 5, 5, 6, 6, 6]

Approach 2: Using list comprehension 

This particular task requires generally 2 loops and list comprehension can perform this particular task in one line and hence reduce the lines of codes and improve code readability. 

Python3




# initializing list of lists
test_list = [4, 5, 6]
 
# printing original list
print("The original list : " + str(test_list))
 
# declaring magnitude of repetition
K = 3
 
# using list comprehension
# repeat elements K times
res = [ele for ele in test_list for i in range(K)]
 
# printing result
print("The list after adding elements : " + str(res))


Output

The original list : [4, 5, 6]
The list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]

Approach 3: Using itertools.repeat() 

This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as the name suggests does the task of repetition and grouping into a list is done by the from_iterable function. 

Python3




import itertools
 
# initializing list of lists
test_list = [4, 5, 6]
 
# printing original list
print("The original list : " + str(test_list))
 
# declaring magnitude of repetition
K = 3
 
# using itertools.chain.from_iterable()
# + itertools.repeat() repeat elements K times
res = list(itertools.chain.from_iterable(itertools.repeat(i, K)
                                         for i in test_list))
 
# printing result
print("The list after adding elements : " + str(res))


Output :

The original list : [4, 5, 6]
The list after adding elements :  [4, 4, 4, 5, 5, 5, 6, 6, 6]

Approach 4: Using extend() method

Approach:

  1. Initialize a list named test_list with some elements.
  2. Print the original list using the print() function along with a message.
  3. Declare the magnitude of repetition, K.
  4. Initialize an empty list named res.
  5. Loop through each element i in the test_list.
  6. Using the extend() method, extend the res list with a new list containing i repeated K times. This is achieved using the * operator to repeat i K times inside a list.
  7. Print the res list using the print() function along with a message.

Python3




# Python3 code to demonstrate
# repeat element K times
 
# initializing list of lists
test_list = [4, 5, 6]
 
# printing original list
print("The original list : " + str(test_list))
 
# declaring magnitude of repetition
K = 3
 
res = []
# repeat elements K times
for i in test_list:
    res.extend([i]*K)
# printing result
print("The list after adding elements : " + str(res))


Output

The original list : [4, 5, 6]
The list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]

Time complexity: O(n), where n is the length of the input list test_list. 
Auxiliary Space: O(n) since we are creating a new list res with a length of k*n.

Approach 5: Using Recursion

The approach to solving the problem of repeating each element K times in a list is to use recursion. Here’s how it works:

  • Check if the list is empty. If the list is empty, return an empty list as the result. This is the base case for the recursion.
  • Get the first element of the list. This element will be repeated K times and added to the result.
  • Get the rest of the list, excluding the first element.
  • Repeat the first element K times and add it to the result.
  • Call the function again with the rest of the list as the input. This will repeat each element in the rest of the list K times.
  • Return the result.

The function will continue to call itself with smaller and smaller parts of the list until the list is empty, at which point it will return an empty list. The repeated elements of each sublist will then be combined with the other sublists to form the final result.

Below is the implementation:

Python3




def repeat_element_k_times(lst, k):
    """
    Repeat each element in a list K times.
 
    :param lst: The list to repeat elements in.
    :param k: The number of times to repeat each element.
    :return: A new list with each element repeated K times.
    """
    if not lst:  # base case: if the list is empty, return an empty list
        return []
    else:
        head = lst[0# get the first element
        tail = lst[1:]  # get the rest of the list
        # repeat head K times and add the result of repeating the tail K times
        return [head] * k + repeat_element_k_times(tail, k)
 
 
# initializing list of lists
test_list = [4, 5, 6]
 
# printing original list
print("The original list : " + str(test_list))
 
# declaring magnitude of repetition
K = 3
 
print("The list after adding elements : " +
      str(repeat_element_k_times(test_list, K)))


Output

The original list : [4, 5, 6]
The list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]

Time complexity: O(n * k), where n is the length of the input list and k is the number of times to repeat each element. This is because the function must repeat each element K times and it must repeat this process for each element in the list, leading to a total of n * k operations.
Auxiliary space: O(n * k), as well. This is because the function creates a new list as the result, which will have n * k elements.

Approach 6: Using numpy:

Step-by-step approach:

  • Initialize an array using numpy.
  • Print the original array.
  • Declare the magnitude of repetition.
  • Use the numpy.repeat() function to repeat the elements K times and store the result in a new array.
  • Print the resulting array.

Python3




import numpy as np
 
# initializing array
arr = np.array([4, 5, 6])
 
# printing original array
print("The original array is: ", arr)
 
# declaring magnitude of repetition
K = 3
 
# using numpy.repeat() function to repeat elements K times
res = np.repeat(arr, K)
 
# printing result
print("The array after adding elements: ", res)


Output:

The original array is:  [4 5 6]
The array after adding elements:  [4 4 4 5 5 5 6 6 6]

Time complexity: The time complexity of numpy.repeat() function is O(KN), where K is the magnitude of repetition and N is the size of the array. Therefore, the overall time complexity of the algorithm is O(KN).
Auxiliary Space: The space complexity of the algorithm is O(KN) because we are creating a new array to store the result of the numpy.repeat() function, which has KN elements.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads