This code:

def reverse(x):
    for i in range(len(x)):
        y[i] = x[-(i+1)]
    return y

a = [1, 2, 3, 4, 5]
b = reverse(a)

returns a "global variable 'y' not defined" error. WHAT GLOBAL VARIABLE?????

If I add 'y = []' anywhere in the code, either inside the function or outside it, I don't get a global variable error, but I get an 'index value out of range' error instead. What's going on?

Comments
nooby question

The reason you're getting the first error is because 'y' is not defined outside the 'for' loop. I'm gonna assume you're using Python since you don't define the data type when declaring a variable. Anyways, what you need to do is declare 'y' outside the loop, so you can then return it (use it). I honestly don't know how you would go about doing that, though, since Python is a bit of a pain with data types.

Within the function, you do, indeed, need to initialize y before you can start defining elements. Even then, if you try to assign elements out of order, that is, an element, [i], when [i-1] is empty, you will get the out of range error:

>>> y=[]
>>> y[8]=5
Traceback (most recent call last):
  File "/base/data/home/apps/runpythoncode/103.348367701639469596/console.py", line 123, in _execStatement
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
IndexError: list assignment index out of range

You can initialize the y list with blanks before you start the loop with list comprehension:

y=[" " for i in xrange(len(x))]

or by list multiplication:

y=len(x)*[" "]

Yep, I'm trying this in both Python 2.7 and Python 3.3. I'm doing it in order to learn Python.

When I add "y = []" directly above the for loop inside the function, I still get an 'index value out of range' error. I've played around with the indices interactively, and "x[-(i+1)] appears to be valid, so I'm still lost.

In Python a variable is defined when you first assign something to it. In your code you never assign anything to y, so it is not defined. You can not use variables that are not defined. As you already figured out, assigning something to y before the loop defines y and thus fixes that error.

Your other problem is that you assign y to be an empty list. For any list y, writing y[i] (whether it's to read from that position or write to it) is only legal if i is a valid index for the list. A valid index for a list of size n is either a non-negative integer less than n or a negative integer greater than or equal to -n. So since your list has a size of 0, there are no valid indices for it (a number can't be less than 0 and non-negative at the same time nor can a negative number be greater than or equal to 0). In other words: it's never legal to write y[i] if y is an empty list.

To add elements to a list you use the append method like y.append(x[-(i+1)]. This adds the given element to the end of the list, increasing its size by one.

Edit: God, I type slowly.

Edited 3 Years Ago by sepp2k

WORKING CODE SNIPPET!!!! YAY!!!!

#! /usr/bin/env python

# This program takes an input string and prints it in reverse order

def reverser(x):
  y = len(x)
  z = ''
  for i in range(len(x)):
    z = z + x[y-1-i:y-i]
  return z

a = raw_input('Type something to be reversed and hit enter: ')
b = reverser(a)
print('Your text in reverse is: "' + b + '"')

Just for reference in future, that if you are not required to avoid it you can of course do this in standard way:

a = raw_input('Type something to be reversed and hit enter: ')
print('Your text in reverse is: "' + a[::-1] + '"')

How about this someone told me about:

import string

def word_reverser(input):
    output = ''
    for a in range(len(input)):
    if input[a] != ' ' and input[a] != ',' and input[a] != '.' and input[a] != '?' and input[a] != '!':
        b = b + input[a]
    else:
        output = output + b[::-1] + input[a]
        output = ''
    return output

c = raw_input('Type anything and hit enter: ')
d = word_reverser(c)
print('Eek, what's this?! ==> ' + d)

There must be a shorter way of doing that too :)

How about this someone told me about:

The code is terrible and not working.

There must be a shorter way of doing that too :)

def word_reverser(word_in):
    return word_in[::-1]

user_input = raw_input('Type anything and hit enter: ')
d = word_reverser(user_input)
print("Eek, what's this?! ==> {}".format(d))
This question has already been answered. Start a new discussion instead.