When it is required to find the index value that has been repeated in a list, it is iterated over using the list comprehension and ‘enumerate’.
Example
Below is a demonstration of the same
my_list = [4, 0, 3, 1] print("The list is :") print(my_list) my_result = [element for sub in ([index] * element for index, element in enumerate(my_list)) for element in sub] print("The result is :") print(my_result)
Output
The list is : [4, 0, 3, 1] The result is : [0, 0, 0, 0, 2, 2, 2, 3]
Explanation
A list is defined and is displayed on the console.
List comprehension is used to iterate through the index values of the list.
The ‘enumerate’ is used to give values to elements of the list.
This is assigned to a variable.
This is displayed as output on the console.