When it is required to repeat elements at custom indices, a simple iteration, enumerate attribute, the ‘extend’ method and the ‘append’ method are used.
Below is a demonstration of the same −
Example
my_list = [34, 56, 77, 23, 31, 29, 62, 99] print("The list is :") print(my_list) index_list = [3, 1, 4, 6] my_result = [] for index, element in enumerate(my_list): if index in index_list: my_result.extend([element, element]) else : my_result.append(element) print("The result is :") print(my_result)
Output
The list is : [34, 56, 77, 23, 31, 29, 62, 99] The result is : [34, 56, 56, 77, 23, 23, 31, 31, 29, 62, 62, 99]
Explanation
A list is defined and displayed on the console.
Another list of integers is defined.
An empty list is defined.
The list is iterated over and enumerate attribute is used, and the elements of the list are compared with the integer list.
If an element is present in the integer list, it is added to the empty list in element’s index using ‘extend’ method.
Otherwise, it is added to empty list using ‘append’ method.
This is the output that is displayed on the console.