You are looping over the list and removing from it. So by the time you get to the halfway point, the second half of the list is gone and the for
loop stops because there are no more items to iterate over anymore.
Print out your list each iteration and you'll see what is happening:
>>> text2 = list('hello')
>>> backwards = []
>>> for char in text2:
... backwards.append(text2[-1])
... del text2[-1]
... print 'char:', char, 'backwards:', backwards, 'text2:', text2
...
char: h, backwards: ['o'] text2: ['h', 'e', 'l', 'l']
char: e, backwards: ['o', 'l'] text2: ['h', 'e', 'l']
char: l, backwards: ['o', 'l', 'l'] text2: ['h', 'e']
The for
loop then stops, because there is no more items to iterate over left; after iterating over indexes 0
, 1
and 2
, the list has been shortened to the point where there is no index 3
anymore.
You could use a while
loop instead:
while text2:
backwards.append(text2[-1])
del(text2[-1])
Now the loop only stops when text2
is entirely empty.
Or you could loop over text
, which has the same length and the same characters in it; it is almost as pointless as your original for
loop because you ignore the char
loop target just the same:
for char in text:
backwards.append(text2[-1])
del(text2[-1])
but text
at least is not being shortened as you loop, so your iteration doesn't end prematurely.
Or you could use a separate index to pick the character to add, adjusting it each iteration, and then not delete from text2
:
index = -1
for character in text2:
backwards.append(text2[index])
index -= 1
Now you'll iterate len(text2)
times. Of course, you then don't need to convert text
to a list anymore, you could just index into text
.