Search code examples
pythonlistinsert

why does conditional list.insert() in python add additional items to list


h = list('camelCase')

for i in range(len(h)):
    if h[i].isupper():
        h.insert(i,' ')

print(h) returns: ['c', 'a', 'm', 'e', 'l', ' ', ' ', ' ', ' ', 'C', 'a', 's', 'e']

I expected: ['c', 'a', 'm', 'e', 'l', ' ', 'C', 'a', 's', 'e']

since there's only one uppercase letter "C"


Solution

  • Your issue is that you are iterating over the range of the list, and when you find a capital letter, you insert the space in that position, which means that the capital letter will be move to the next position, therefore once you find a capital letter it will simply add a space and check that letter again.

    Your h[i] right now would print the following:

    `c`, `a`, `m`, `e`, `l`, `C`, `C`, `C`, `C` 
    

    My recommendation would be to not modify the original list, but do it in a separate one:

    h = list('camelCase')
    new_text = ''
    
    for i in range(len(h)):
        if h[i].isupper():
            new_text += ' '
        new_text += h[i]