DEV Community

Flávia Bastos
Flávia Bastos

Posted on • Originally published at on

Map a string in Python with enumerate

Problem: create a map of the letters and indices in a string.

My first approach was to loop over the string using range(len(s)), and checking if the letter exists in the map before adding it:

    s = 'mozzarella'
    mapped_s = {}
    for i in range(len(s)):
        if s[i] in mapped_s:
            mapped_s[s[i]] = [i]
    print(f' mapped: {mapped_s}')

That works:

{'m': [0], 'o': [1], 'z': [2, 3], 'a': [4, 9], 'r': [5], 'e': [6], 'l': [7, 8]}

but there’s a more pythonic way of getting this map: use enumerate()!

    letters = 'mozzarella'
    mapped_s = collections.defaultdict(list)
    for index, letter in enumerate(letters):
    print(f'mapped: {dict(mapped_s)}')

Enumerate is a python built-in function that gives you a list of tuples of the indices and the elements in an iterable:

print(f'enum {list(enumerate('mozzarella'))}')
enum [(0, 'm'), (1, 'o'), (2, 'z'), (3, 'z'), (4, 'a'), (5, 'r'), (6, 'e'), (7, 'l'), (8, 'l'), (9, 'a')]

It can be used to loop over the iterable while keeping track of the index and the element similar to what _range(len(s)) _was doing in my first example:

    for i, element in enumerate('mozzarella'):
        print(f'{i}: {element}')

It also removes the need to check if the letter already exists before creating that letter’s map!

You can read more about enumerate in the docs or this super nice article by Dan Bader.

The post Map a string in Python with enumerate was originally published on

Top comments (0)