Python – Character indices Mapping in String List

When it is required to find character indices that map to a string list, a simple iteration, list comprehension and ‘add’ method is used.


Below is a demonstration of the same −

from collections import defaultdict

my_list = ['p y t h o n', 'i s', 'f u n', 't o', 'l e a r n']

print("The list is :")

my_result = defaultdict(set)

for index, element in enumerate(my_list):
   for sub in element.split():
      my_result[sub].add(index + 1)

my_result = {key: list(val) for key, val in my_result.items()}

print("The result is :")


The list is :
['p y t h o n', 'i s', 'f u n', 't o', 'l e a r n']
The result is :
{'p': [1], 'y': [1], 't': [1, 4], 'h': [1], 'o': [1, 4], 'n': [1, 3, 5], 'i': [2], 's': [2], 'f': [3], 'u': [3], 'l': [5], 'e': [5], 'a': [5], 'r': [5]}


  • The required packages are imported into the environment.

  • A list is defined and displayed on the console.

  • An empty dictionary is created using defaultdict.

  • The list is iterated over using the ‘enumerate’ attribute.

  • The ‘split’ method is used to split every element, and the ‘add’ method is used to add the element at a specific index in the dictionary.

  • A dictionary comprehension is used to iterate over elements in the dictionary.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021


Kickstart Your Career

Get certified by completing the course

Get Started