
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Python - Index Ranks of Elements
- Swap Even Index Elements And Odd Index Elements in Python
- Python Pandas - Repeat elements of an Index
- Python – Elements with same index
- Python - Make new Pandas Index with deleting multiple index elements
- Python Program that print elements common at specified index of list elements
- Equate two list index elements in Python
- Python – Check if elements index are equal for list elements
- Python – Extract elements in between multiple specific range of index
- Python Pandas - Return number of unique elements in the Index object
- Python Pandas - Return a new Index with elements of index not in other and get the difference
- Python Pandas - Return a new Index with elements of index not in other but unsort the result
- Python Pandas - Return the Number of elements in the underlying Index data
- Python – Check if elements in a specific index are equal for list elements
- Python prorgam to remove duplicate elements index from other list

Advertisements