Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Merge Range Characters in List
Next article icon

Character Indices Mapping in String List – Python

Last Updated : 13 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Python | Merge Range Characters in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
    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
  • Python | Pair the consecutive character strings in a list
    Sometimes while programming, we can face a problem in which we need to perform consecutive element concatenation. This problem can occur at times of school programming or competitive programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + z
    5 min read
  • Find position of a character in given string - Python
    Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
    2 min read
  • Python - Convert Strings to Character Matrix
    Sometimes, while dealing with String lists, we can have a problem in which we need to convert the Strings in list to separate character list. Overall converting into Matrix. This can have multiple applications in data science domain in which we deal with lots of data. Lets discuss certain ways in wh
    3 min read
  • Create a List of Strings in Python
    Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences