# Python – Index Value repetition in List

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

Updated on 16-Sep-2021 09:22:21