'why does conditional list.insert() in python add additional items to list [duplicate]
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 1:[1]
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]
Solution 2:[2]
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
Solution 3:[3]
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)
Hope it could help you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shunya |
| Solution 2 | Violet |
| Solution 3 |
