-1

I'm having an issue with variable and function. Here is a simple code:

r = 0
list = ['apple','lime','orange']
def list_list(x):
    for i in x:
        r +=1
        print r
list_list(list)

Error:

UnboundLocalError: local variable 'r' referenced before assignment

I know it must be something simple. I started to do my script using functions instead straight code.

amb1s1
  • 1,995
  • 5
  • 22
  • 26

3 Answers3

3

You should rewrite your function to take r as an argument if you want to define it outside of your function:

def my_func(some_list, r=0):
    # do some stuff

Basically, you have a problem with scope. If you need r outside of the function, just return it's value in a tuple:

def my_func(some_list, r=0):
    # do some stuff

    return new_list, r

my_list = [1,2,3,4,5]
different_list, my_outside_r = my_func(some_list, 0)
BenDundee
  • 4,389
  • 3
  • 28
  • 34
2

The r within the function isn't the same as the one outside the function, so it hasn't been set yet.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
Peter Wooster
  • 6,009
  • 2
  • 27
  • 39
1

You shoudld put r = 0 inside the function. But if you want the length of the list just use len(list)

Also try to avoid naming variables same as builtin names like list.

jurgenreza
  • 5,856
  • 2
  • 25
  • 37