Character Indices Mapping in String List - Python
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:
- For each string in the list a list comprehension generates
(character, index)
pairs using enumerate
. - Each list of pairs is appended to
ch
creating a list of character-index mappings for all strings which is then printed
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:
- For each string a dictionary is created using {char: idx for idx, char in enumerate(string)}, mapping each character to its index.
- List comprehension stores these dictionaries in c resulting in a list of dictionaries representing character-index mappings for each string which is then printed.
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:
- For each string defaultdict(list) maps each character to a list of all its indices using m[char].append(idx) during iteration with enumerate.
- Each defaultdict is converted to a regular dictionary and appended to c resulting in a list of dictionaries mapping characters to their respective indices for each string.
Similar Reads
Python - Fill list characters in String Given String and list, construct a string with only list values filled. Input : test_str = "geeksforgeeks", fill_list = ['g', 's', 'f', k] Output : g__ksf__g__ks Explanation : All occurrences are filled in their position of g, s, f and k. Input : test_str = "geeksforgeeks", fill_list = ['g', 's'] Ou
9 min read
Split String into List of characters in Python We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read
Python | String List to Column Character Matrix Sometimes, while working with Python lists, we can have a problem in which we need to convert the string list to Character Matrix where each row is String list column. This can have possible application in data domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using
5 min read
Python | Merge Range Characters in List Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in development domain to merge the names into one element. Letâs discuss certain ways in which this can be perf
6 min read
Python - Characters Index occurrences in String Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read
Python | Convert string List to Nested Character List Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehen
7 min read