When it is required to display elements with same index, a simple iteration and the ‘enumerate’ attribute is used.
Below is a demonstration of the same −
my_list = [33, 1, 2, 45, 41, 13, 6, 9] print("The list is :") print(my_list) my_result = [] for index, element in enumerate(my_list): if index == element: my_result.append(element) print("The result is :") print(my_result)
The list is : [33, 1, 2, 45, 41, 13, 6, 9] The result is : [1, 2, 6]
A list is defined and displayed on the console.
An empty list is defined.
The list is iterated over, and the element is compared with the index.
If it is equal, it is appended to the empty list.
This is the output that is displayed on the console.