
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Elements with Same Index
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 −
Example
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)
Output
The list is : [33, 1, 2, 45, 41, 13, 6, 9] The result is : [1, 2, 6]
Explanation
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.
Advertisements