Python Program to repeat elements at custom indices
Last Updated :
19 Apr, 2023
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))
OutputThe 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))
OutputThe 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:
- Import the numpy library.
- Convert the original list to a numpy array using the numpy.array() function.
- Create a boolean mask to identify the custom elements. We can use the numpy.isin() function to create this mask.
- Use the numpy.repeat() function to repeat the custom elements identified by the boolean mask.
- Use the numpy.concatenate() function to combine the repeated custom elements with the original array.
- Convert the result back to a list using the tolist() function.
- 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:
- Initialize an empty heap.
- 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).
- 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 - index by adding 1 to their index.
- 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.
OutputThe 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.
Similar Reads
Python program to replace first 'K' elements by 'N'
Given a List, replace first K elements by N. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3 Output : [3, 3, 3, 3, 4, 2, 6, 9] Explanation : First 4 elements are replaced by 3. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10 Output : [10, 10, 6, 8, 4, 2, 6, 9] Explanation : Fi
5 min read
Python - Custom element repetition
Given list of elements and required occurrence list, perform repetition of elements. Input : test_list1 = ["Gfg", "Best"], test_list2 = [4, 5] Output : ['Gfg', 'Gfg', 'Gfg', 'Gfg', 'Best', 'Best', 'Best', 'Best', 'Best'] Explanation : Elements repeated by their occurrence number. Input : test_list1
6 min read
Python - Repeat Alternate Elements in list
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
7 min read
Repeat Each Element K times in List - Python
The task of repeating each element k times in a list in Python involves creating a new list where each element from the original list appears k times consecutively. For example, given the list a = [4, 5, 6] and k = 3, the goal is to produce [4, 4, 4, 5, 5, 5, 6, 6, 6]. Using list comprehensionList c
3 min read
Python - Remove elements at Indices in List
Given List, remove all the elements present in the indices list in Python. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5]Â Output : [5, 6, 7, 2, 10]Â Explanation : 3, 6, and 1 has been removed. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2]Â Output : [5, 6, 7, 8,
7 min read
Python program to Mark duplicate elements in string
Given a list, the task is to write a Python program to mark the duplicate occurrence of elements with progressive occurrence number. Input : test_list = ['gfg', 'is', 'best', 'gfg', 'best', 'for', 'all', 'gfg'] Output : ['gfg1', 'is', 'best1', 'gfg2', 'best2', 'for', 'all', 'gfg3'] Explanation : gfg
3 min read
Python - Incremental and Cyclic Repetition of List Elements
Sometimes, while working with Python lists, we can have a problem in which we need to repeat elements K times. But we can have variations in this and have to repeat elements in cyclic and incremental way. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + enumer
4 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Python - Odd elements indices
Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Letâs discuss certain way to find indic
7 min read
Python Program that prints elements common at specified index of list elements
Given a list of strings, the task is to write a Python program to extract all characters that are same at a specified index of each element of a list. Illustration: Input : test_list = ["geeks", "weak", "beak", "peek"] Output : ['e', 'k'] Explanation : e and k are at same at an index on all strings.
5 min read