Python - Index Directory of Elements

PythonServer Side ProgrammingProgramming

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.

raja
Updated on 15-Sep-2021 12:03:54

Advertisements