Open In App

Python Program to repeat elements at custom indices

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Input : test_list = [4, 6, 7, 3, 1, 9, 2, 19], idx_list = [1, 6] 
Output : [4, 6, 6, 7, 3, 1, 9, 2, 2, 19] 
Explanation : All required index elements repeated, 6 repeated as it is at index 1. 

Method 1: Using loop and extend()

In this, we perform the task of repeating each element in case it is the required index to be repeated using extend() and loop is used to iterate for every index. The enumerate() is used to get all the indices along with elements.

Program:

Python3




# initializing list
test_list = [4, 6, 7, 3, 1, 9, 2, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing index list
idx_list = [3, 1, 4, 6]
 
res = []
for idx, ele in enumerate(test_list):
    if idx in idx_list:
         
        # incase of repetition
        res.extend([ele, ele])
    else :
        res.append(ele)
 
# printing result
print("The Custom elements repetition : " + str(res))


Output:

The original list is : [4, 6, 7, 3, 1, 9, 2, 19]

The Custom elements repetition : [4, 6, 6, 7, 3, 3, 1, 1, 9, 2, 2, 19]

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

Method 2: Using List Comprehension

Use list comprehension to achieve the same result as the given program.

Python3




test_list = [4, 6, 7, 3, 1, 9, 2, 19]
idx_list = [3, 1, 4, 6]
 
res = []
for idx, ele in enumerate(test_list):
    if idx in idx_list:
        res.extend([ele, ele])
    else:
        res.append(ele)
 
print("The Custom elements repetition : " + str(res))


Output

The Custom elements repetition : [4, 6, 6, 7, 3, 3, 1, 1, 9, 2, 2, 19]

Time complexity: O(n), where n is the length of the test_list. 
Auxiliary space: O(n), because we create a new list res to store the modified version of test_list.

Method 3 : Using the map() function and a lambda function

Step by step approach:

  • Initialize the test_list and idx_list as before.
  • Create a lambda function that takes an index i and returns the element of test_list at that index if i is not in idx_list, otherwise it returns a list containing the element at that index repeated twice.
  • Use the map() function to apply the lambda function to each index in range(len(test_list)). This returns a new iterable containing the results.
  • Convert the result iterable to a list and flatten it by using a list comprehension to iterate over each sublist and append its elements to a new list.
  • Print the final result.

Python3




test_list = [4, 6, 7, 3, 1, 9, 2, 19]
idx_list = [3, 1, 4, 6]
 
res = list(map(lambda i: [test_list[i], test_list[i]] if i in idx_list else [test_list[i]], range(len(test_list))))
flat_res = [item for sublist in res for item in sublist]
 
print("The Custom elements repetition : " + str(flat_res))


Output

The Custom elements repetition : [4, 6, 6, 7, 3, 3, 1, 1, 9, 2, 2, 19]

The time complexity of this approach is O(n), where n is the length of the input list, because we iterate over each element of the list once. 

The auxiliary space is also O(n), because we create a new list with the same length as the input list to store the results.

Method 4: using the numpy library. 

 steps for the numpy approach:

  1. Import the numpy library.
  2. Convert the original list to a numpy array using the numpy.array() function.
  3. Create a boolean mask to identify the custom elements. We can use the numpy.isin() function to create this mask.
  4. Use the numpy.repeat() function to repeat the custom elements identified by the boolean mask.
  5. Use the numpy.concatenate() function to combine the repeated custom elements with the original array.
  6. Convert the result back to a list using the tolist() function.
  7. Print the final result.

Python3




import numpy as np
 
test_list = [4, 6, 7, 3, 1, 9, 2, 19]
idx_list = [3, 1, 4, 6]
 
arr = np.array(test_list)
mask = np.isin(np.arange(len(arr)), idx_list)
repeated_custom = np.repeat(arr[mask], 2)
result = np.concatenate([arr[~mask], repeated_custom]).tolist()
 
print("The Custom elements repetition : " + str(result))


OUTPUT:
The Custom elements repetition : [4, 7, 9, 19, 6, 6, 3, 3, 1, 1, 2, 2]

Time Complexity: The time complexity of this approach is O(n), where n is the length of the original list.
Auxiliary Space: The auxiliary space required by this approach is O(n), where n is the length of the original list.

Method 5: using heapq:

Algorithm:

  1. Initialize an empty heap.
  2. Iterate over the given index list and add the corresponding element of the given list to the heap as a tuple of the form (index, value).
  3. While the heap is not empty:
    a. Pop the element with the smallest index from the heap.
    b. Insert the popped value at the corresponding index in the given list.
    c. Update the indices of the remaining elements in the heap that are greater than or equal to the popped
  4. index by adding 1 to their index.
  5. Return the modified given list.

Python3




import heapq
 
test_list = [4, 6, 7, 3, 1, 9, 2, 19]
idx_list = [3, 1, 4, 6]
 
heap = []
for idx in idx_list:
    if idx < len(test_list):
        heapq.heappush(heap, (idx, test_list[idx]))
while heap:
    idx, value = heapq.heappop(heap)
    test_list.insert(idx, value)
    for i in range(len(heap)):
        if heap[i][0] >= idx:
            heap[i] = (heap[i][0]+1, heap[i][1])
 
print("The Custom elements repetition : " + str(test_list))
#This code is contributed by Rayudu.


Output

The Custom elements repetition : [4, 6, 6, 7, 3, 3, 1, 1, 9, 2, 2, 19]

Time Complexity:  O(n log n), where n is the length of the given list. The loop that iterates over the index list has a time complexity of O(k), where k is the length of the index list, which is typically much smaller than n. The operations of inserting and popping from a heap have a time complexity of O(log n). Hence, the dominant factor in the time complexity is the sorting and merging of the elements, which has a time complexity of O(n log n).

Space Complexity:  O(n), where n is the length of the given list. The additional space required is for the heap, which can have at most k elements, where k is the length of the index list. Since k is typically much smaller than n, the space complexity is dominated by the size of the given list.



Last Updated : 19 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads