Character Indices Mapping in String List Python (original) (raw)

Last Updated : 13 Feb, 2025

We are given a string list we need to map characters to their indices. **For example, a = [“hello”, “world”] so that output should be [[(‘h’, 0), (‘e’, 1), (‘l’, 2), (‘l’, 3), (‘o’, 4)], [(‘w’, 0), (‘o’, 1), (‘r’, 2), (‘l’, 3), (‘d’, 4)]].

Using a nested for loop

A nested for loop iterates through each string in the list and then through each character within string. It maps each character to its corresponding index in the string creating a detailed character-index mapping.

Python `

a = ["hello", "world"]

ch = []

for string in a:

# Create a list of (char, index) pairs for each string
c = [(char, idx) for idx, char in enumerate(string)]
ch.append(c)

print(ch)

`

Output

[[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]]

**Explanation:

Using dictionary comprehension

Dictionary comprehension can be used to map each character to its index in the string by iterating with enumerate. This approach creates a dictionary for each string providing direct access to character indices.

Python `

a = ["hello", "world"]

Create a list of dictionaries for each string

c = [{char: idx for idx, char in enumerate(string)} for string in a]

print(c)

`

Output

[{'h': 0, 'e': 1, 'l': 3, 'o': 4}, {'w': 0, 'o': 1, 'r': 2, 'l': 3, 'd': 4}]

**Explanation:

Using defaultdict from collections

defaultdict from collections can be used to group character indices in a list allowing multiple occurrences of the same character to be stored. It automatically initializes empty lists for new characters simplifying mapping process.

Python `

from collections import defaultdict

a = ["hello", "world"] c = []

for string in a:

# Create a defaultdict to map characters to indices
m = defaultdict(list)
for idx, char in enumerate(string):
    m[char].append(idx)
c.append(dict(m))

print(c)

`

Output

[{'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}, {'w': [0], 'o': [1], 'r': [2], 'l': [3], 'd': [4]}]

**Explanation: