1

When I type this:

def FirstReverse(str): 

 # code goes here

x = len(str)

s = list(str)

while x >= 0:
 print s[x]
 x = x - 1

# keep this function call here  
# to see how to enter arguments in Python scroll down
print FirstReverse(raw_input())

I get this error

ERROR ::--Traceback (most recent call last):
File "/tmp/105472245/main.py", line 14, in <module>
print FirstReverse("Argument goes here")
File "/tmp/105472245/main.py", line 7, in FirstReverse
print s[x] IndexError: list index out of range
rayryeng
  • 102,964
  • 22
  • 184
  • 193

3 Answers3

1

Got it actually, Here's the answer!

>> x = list(‘1234’)

>> x

[‘1’ , ‘2’ , ‘3’, ‘4’]

>> length = len(x)

4

>> x[length]

Index Error: list index out of range NOTE : The list index start from zero(0).

But here the length is four.

The assignment of above list is like:

x[0] = 1

x[1] = 2

x[2] = 3

x[3] = 4

x[4] = ?

If you try to access the x[4] which is None or Empty, the list index out of range will come.

Poojan
  • 3,366
  • 2
  • 17
  • 33
1

Python indexing begins at 0. So, say for the string "Hello", the index 0 points to "H" and the index 4 points to "o". When you do:

x = len(str)

You are setting x to 5, rather than the maximum index of 4. So, try this instead:

x = len(str) - 1

Also, another pointer. Rather than:

x = x - 1

You can simply put:

x -= 1
1

Check the best way to reverse the list first.. I think your reverse implementation maybe not right. There are four(4) possible ways to reverse the list..

my_list = [1, 2, 3, 4, 5]

# Solution 1: simple slicing technique..
print(my_list[::-1]) 

# Solution 2: use magic method __getitem__ and 'slice' operator
print(my_list.__getitem__(slice(None, None, -1))) 

# Solution 3: use built-in list.reverse() method. Beware this will also modify the original sort order
print(my_list.reverse())

# Solution 4: use the reversed() iteration function
print(list(reversed(my_list)))
Temizzi
  • 402
  • 2
  • 10
  • Method 2 is probably too much for a beginner. Also, we've already determined why the reverse method of the OP doesn't work. – rayryeng Feb 09 '19 at 18:03
  • Method 1, 3 & 4 are good enough for beginner.. It just for personal preference.. But just beware that method 3 will also modify the order of positional parameter. – Temizzi Feb 09 '19 at 19:31