- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 - Index Directory of Elements
When it is required to index directory of elements in a list, list comprehension along with ‘set’ operator is used.
Example
Below is a demonstration of the same
my_list = [81, 36, 42, 57, 68, 12, 26, 26, 38] print("The list is :") print(my_list) my_result = {key: [index for index, value in enumerate(my_list) if value == key] for key in set(my_list)} print("The result is :") print(my_result)
Output
The list is : [81, 36, 42, 57, 68, 12, 26, 26, 38] The result is : {36: [1], 68: [4], 38: [8], 42: [2], 12: [5], 81: [0], 57: [3], 26: [6, 7]}
Explanation
A list is defined and is displayed on the console.
The list comprehension is used to iterate through the list and check for a specific condition.
This is converted to a dictionary and then assigned to a variable.
This is the variable that is displayed as output on the console.
Advertisements