0

I am trying to manually (without the built in function) reverse a string of text, however the code gives me a "list assignment index out of range" for list_rev[u] = list_[i]. I don't understand why that happens? What I am trying to do is take the text from the list_ and place it in list_rev in a reverse order and then print list_rev.

Thanks!

text = raw_input("Word?")

text = str(text)

def reverse(text):
    list_rev = []
    list_ = []
    length = int(len(text))
    k = 0
    while k < (length):
        list_.append(str(text)[k])
        k += 1

    i = int(length-1)
    u = 0
    while i >= 0:
        list_rev[u] = list_[i]
        u += 1
        i -= 1
    return list_rev,

print reverse(text)
MattDMo
  • 100,794
  • 21
  • 241
  • 231
Alexander Nilsson
  • 121
  • 1
  • 1
  • 5
  • 5
    `my_string = "foo bar baz"; reversed_string = my_string[::-1]` – MattDMo Apr 08 '13 at 16:58
  • you need to append to list_rev, it is of size 0 and you never change its size. apart from that, this is horrendous code for too many reasons.... –  Apr 08 '13 at 17:01

5 Answers5

1

You receive the error "list assignment index out of range" from the expression list_rev[u] because the index (u) is outside the range 0 .. len(list_rev)-1. In particular, list_rev is empty, so there are no possible values of u that refer to a valid element of list_rev.

If you want to add a new element to list_rev, try .append(), .extend(), or .insert().

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

You can append characters to the list:

text = raw_input("Word?")

text = str(text)

def reverse(text):
    list_rev = []
    list_ = []
    length = int(len(text))
    k = 0
    while k < (length):
        list_.append(str(text)[k])
        k += 1

    i = int(length-1)
    u = 0
    while i >= 0:
        list_rev.append(list_[i])
        i -= 1
    return list_rev,

print reverse(text)

Output:

Word?qwerty
(['y', 't', 'r', 'e', 'w', 'q'],)
4d4c
  • 8,049
  • 4
  • 24
  • 29
0

list_rev is an empty list : you have to append the char :

text = raw_input("Word?")

text = str(text)

def reverse(text):
    list_rev = []
    list_ = []
    length = int(len(text))
    k = 0
    while k < (length):
        list_.append(str(text)[k])
        k += 1

    i = int(length-1)
    u = 0
    while i >= 0:
        list_rev.append(  list_[i] )
        u += 1
        i -= 1
    return list_rev

print ''.join(  str(elem) for elem in reverse(text) )
lucasg
  • 10,734
  • 4
  • 35
  • 57
0

You can also simply solve this as below using insert,

def reverse(text):
    reverse_list = []
    for a in text:
        reverse_list.insert(0,a)
    return "".join(reverse_list)

text = raw_input("Word?")

reverse_text = reverse(text)

print reverse_text
Yuv
  • 202
  • 3
  • 12
0

Another option using strings;

def reverse(text):
  reversed = ''
  for index in range(len(text)-1, -1, -1):
    reversed += text[index]
  return reversed