Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Repeat each element K times in list

Improve Article
Save Article
  • Last Updated : 01 Feb, 2023
Improve Article
Save Article

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. 

Repeat Each Element in a List in Python using 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.

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]

Repeat Each Element in a List in Python 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]

Repeat Each Element in a List in Python 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]

Using extend() method

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]

Repeat Each Element in a List in Python 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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!