1
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"

Jafeth Yahuma
  • 71
  • 1
  • 5
  • 2
    Try putting `print(h, i, h[i])` before `if h[i].isupper():` and see what is happening. Usually it is not good to modify a list during a `for` loop over the list. – j1-lee May 15 '22 at 05:54

3 Answers3

1

You need to copy the original list first.

The reason the space letters are added repeatedly is that " " is added in the list h so "C" is taken continuously until the index i reaches the original length of h.

h = list('camelCase')
a = h.copy()

for i in range(len(h)):
    if h[i].isupper():
        a.insert(i,' ')
print(a)
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Metalgear
  • 3,391
  • 1
  • 7
  • 16
1

Changing the list you are iterating on isn't always a good idea but if you want to apply it on the same list you can use while loop:

h = list('camelCase')

i = 0
while (i < len(h)):
    if h[i].isupper():
        h.insert(i,' ')
        i += 1
    i += 1
Violet
  • 33
  • 7
0

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]
Shunya
  • 2,344
  • 4
  • 16
  • 28