0

I am writing a function to take a string and reverse it. I can't work out why my code is returning a reversed string but with only half of the letters of the string passed to it.

   def reverse(text):
        temp = []
        reverse_text = ""
        for i in text:
            temp.append(i)
        for i in temp:
            reverse_text += temp.pop()
        print reverse_text
shfury
  • 389
  • 1
  • 5
  • 15
  • 2
    You are modifying the list while you are iterating over it **with a for loop**. This will almost always get you in trouble. – Jasper Nov 14 '15 at 10:45
  • See this: http://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list – devautor Nov 14 '15 at 10:59

6 Answers6

4

I'm not going to post a complete answer, but:

  1. Don't modify a list you're iterating over with a for loop. Bad things will happen (you already realized that)

  2. You therefore can use a while loop to accomplish the task.

  3. You can also use a for loop, but then you'll end up with for i in range(len(temp)): (see other answers), and the range(len(..)) construct is rather "unpythonic".

Jasper
  • 3,939
  • 1
  • 18
  • 35
1
def reverse(text)
    return text[::-1]
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0

I would just use reversedString = string[::-1], most easy way I think.

Tenzin
  • 2,415
  • 2
  • 23
  • 36
0
for i in range(len(text)):
    reverse_text += temp.pop()

don't change the string.

aristotll
  • 8,694
  • 6
  • 33
  • 53
0

Every time you are doing pop operation you are changing the temp over which you are iterating as well.

A simple way would be to just do pop n times where n is the length of temp

def reverse(text):
    temp = []
    reverse_text = ""
    for i in text:
        temp.append(i)
    print temp
    for i in range(len(temp)):
#         print i, temp[i]
        reverse_text += temp.pop()
    print reverse_text
MARK
  • 2,302
  • 4
  • 25
  • 44
0

If you can't do:

text[::-1]

Try doing a for loop:

text = 'Hello'
product=''
for x in range(len(text)-1, -1, -1):
    product+=text[x]
return product
Chris Nguyen
  • 160
  • 1
  • 4
  • 14