Open In App

Python – Repeat Alternate Elements in list

Last Updated : 26 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many times we have this particular use-case in which we need to repeat alternate element of list K times. The problems of making a double clone has 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.

Method #1 : 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 improving code readability. 

Python3




# Python3 code to demonstrate
# Alternate Element Repetition
# using list comprehension
 
# 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
# Alternate Element Repetition
res = [ele for idx, ele in enumerate(test_list)
       for i in range(K) if idx % 2 == 0]
 
# printing result
print("The list after alternate repeating elements : " + str(res))


Output

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

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using itertools.chain.from_iterable() + itertools.repeat() This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as name suggests does the task of repetition and grouping into a list is done by the from_iterable function. 

Python3




# Python3 code to demonstrate
# Alternate Element Repetition
# using itertools.chain.from_iterable() + itertools.repeat()
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()
# Alternate Element Repetition
res = list(itertools.chain.from_iterable(itertools.repeat(ele, K)
                                         for idx, ele in enumerate(test_list) if idx % 2 == 0))
 
# printing result
print("The list after alternate repetition elements : " + str(res))


Output

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

Time complexity: O(n) as it requires iterating through the original list of size n and repeating each element K times, resulting in a total of n*K operations.
Auxiliary space: O(n*K) as it creates a new list to store the result of the repeated elements.

Method #3 : Using extend() method and * operator

Python3




# Python3 code to demonstrate
# Alternate Element Repetition
 
# 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=[]
for i in range(0,len(test_list)):
    if(i%2==0):
        res.extend([test_list[i]]*K)
         
 
# printing result
print("The list after alternate repeating elements : " + str(res))


Output

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

Time complexity: O(n), where n is the length of the input list. The loop runs n times.
Auxiliary space: O(K), where K is the magnitude of repetition.

Method #4: Using slicing and extend() method 

Step-by-step approach:

  • Initialize a list of lists named test_list with some values.
  • Use list slicing to create a new list named alternate_list that contains every other element of the test_list.
  • The slice test_list[::2] means start from the beginning of the list and take every second element. Store the result in alternate_list.
  • Print the original list using the print() function. The statement is print(“The original list : ” + str(test_list)).
  • Declare the magnitude of repetition K. In this case, K = 3.
  • Create an empty list named res to store the final result.
  • Use a loop to iterate over each element of the alternate_list. For each element, create a new list with the repeated element K times using the extend() method.
  • Append the new list to the res list
  • Print the final list after repeating alternate elements K times using the print() function. 

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Alternate Element Repetition
 
# initializing list of lists
test_list = [4, 5, 6]
alternate_list = test_list[::2]
# printing original list
print("The original list : " + str(test_list))
 
# declaring magnitude of repetition
K = 3
res = []
for i in range(len(alternate_list)):
    res.extend([alternate_list[i]]*K)
 
 
# printing result
print("The list after alternate repeating elements : " + str(res))


Output

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

The time complexity of this code is O(N), where N is the length of the original list test_list.

 The auxiliary space used by this code is O(N), where N is the length of the original list test_list. 

Method #5 :  Here’s another approach using the numpy library:

Note: Install numpy module using command “pip install numpy”

Python3




# Python3 code to demonstrate
# Alternate Element Repetition
import numpy as np
# printing original list
test_list = [4, 5, 6]
K = 3
 
res = np.repeat(np.array(test_list[::2]), K).tolist()
# printing result
print("The list after alternate repeating elements :", res)
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The list after alternate repeating elements : [4, 4, 4, 6, 6, 6]

Time Complexity: O(n), where n is the length of the input list. The time complexity is linear with the length of the list as it is just repeating and converting the elements in the list.
Auxiliary Space: O(n), where n is the length of the output list after repeating the elements. The space complexity is linear with the length of the output list as it requires memory to store the repeated elements.

Method 6: Using map()+ lambda function

Uses a map() function with a lambda function to repeat the selected elements K times, and the extend() function to append the repeated elements to a new list.

  • Initialize the list test_list with some values.
  • Print the original list using the print() function and string concatenation.
  • Declare the magnitude of repetition as K.
  • Initialize an empty list res to store the alternate repeated elements.
  • Iterate through the elements in test_list using the enumerate() function.
  • Check if the index of the current element is even using the modulo operator %.
  • If the index is even, use a map() function with a lambda function to repeat the selected element K times.
  • Use the extend() function to append the repeated elements to the res list.
  • Print the resulting list using the print() function and string concatenation.

Below is the implementation of the above approach:

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 map and lambda function for alternate element repetition
res = []
for i, val in enumerate(test_list):
    if i % 2 == 0:
        res.extend(map(lambda x: val, range(K)))
 
# Printing result
print("The list after alternate repeating elements: " + str(res))


Output

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

Time complexity: O(NK) where N is the length of the input list.
Auxiliary space: O(NK)

Method #7 : Using extend()+operator.mul() methods

Approach

  1. Initiate a for loop with index from 0 to length of list
  2. Find alternate element index by checking if the index is divisible by 2
  3. Access the alternate element by index and repeat element by using operator.mul() and append it to output list
  4. Display output list

Python3




# Python3 code to demonstrate
# Alternate Element Repetition
 
# 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=[]
import operator
for i in range(0,len(test_list)):
    if(i%2==0):
        res.extend(operator.mul([test_list[i]],K))
         
 
# printing result
print("The list after alternate repeating elements : " + str(res))


Output

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

Time complexity: O(NK) where N is the length of the input list.
Auxiliary space: O(NK)



Previous Article
Next Article

Similar Reads

Python Program to repeat elements at custom indices
Given a List, the following program repeats those elements which are at a custom index, these custom indices are provided to it as a separate list. Input : test_list = [4, 6, 7, 3, 1, 9, 2, 19], idx_list = [3, 1, 6] Output : [4, 6, 6, 7, 3, 3, 1, 9, 2, 2, 19] Explanation : All required index elements repeated, Eg. 6 repeated as it is at index 1. In
6 min read
Python | Repeat each element K times in list
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:
7 min read
Python | Repeat and Multiply list extension
Sometimes, while working with Python list, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat contents of list and while doing that, each time new list must be a multiple of original list. This incremental expansion has applications in many domains. Let's discuss a way in which this task can be p
6 min read
Repeat all the elements of a NumPy array of strings
Let us see how to repeat all elements of the given array of string 3 times. Example : Input : ['Akash', 'Rohit', 'Ayush', 'Dhruv', 'Radhika'] Output : ['AkashAkashAkash', 'RohitRohitRohit', 'AyushAyushAyush', 'DhruvDhruvDhruv', 'RadhikaRadhikaRadhika'] We will be using the numpy.char.multiply(a, i) method for this task. numpy.char.multiply(a, i) Sy
2 min read
Python | List consisting of all the alternate elements
Some of the list operations are quite general and having shorthands without needing to formulate a multiline code is always required. Wanting to construct a list consisting of all the alternate elements of the original list is a problem that one developer faces in day-day applications. Let's discuss certain ways to print all the alternate elements
7 min read
Python | Multiplying Alternate elements in List
The problem of getting product of a list is quite generic and we might some day face the issue of getting the product of alternate elements and get the list of 2 elements containing product of alternate elements. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + list slicing + loop List slicing clubbe
3 min read
Python - Alternate List elements
Given 2 lists, print the element in zig-zag manner, i.e print similar indices of lists and then proceed to next. Input : test_list1 = [5, 3, 1], test_list2 = [6, 4, 2] Output : [5, 6, 3, 4, 1, 2, 4] Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on. Input : test_list1 = [5, 3, 1, 9], test_list2 = [6, 4,
4 min read
Python - Alternate list elements as key-value pairs
Given a list, convert it into dictionary by mapping alternate elements as key-value pairs. Input : test_list = [2, 3, 5, 6, 7, 8] Output : {3: 6, 6: 8, 2: 5, 5: 7} Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate] Input : test_list = [2, 3, 5, 6] Output : {3: 6, 2: 5} Explanation : Alternate elements mapped to g
2 min read
Python - Check alternate peak elements in List
Given a list, the task is to write a Python program to test if it's alternate, i.e next and previous elements are either both smaller or larger across the whole list. Input : test_list = [2, 4, 1, 6, 4, 8, 0] Output : True Explanation : 4, 6, 8 are alternate and peaks (2 1). Input : test_list = [2, 4, 1, 6, 4, 1, 0] Output : False Explanation : 1 i
3 min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Practice Tags :