1

I have a sample python code here, it intrigues me a lot....

listt = ['hii']
var = 0

def fool():
    listt.append('p')
    var += 10

fool()
print(listt)
print(var)

I obviously get an error in function that var is referred before assignment, but why not for listt ?

  • `list` is mutable object, `int` is not. – buran Jul 06 '21 at 10:05
  • 2
    @buran irrelevant – juanpa.arrivillaga Jul 06 '21 at 10:07
  • 2
    If you assign to a variable anywhere in the body of a function, it is considered local unless explicitely declared global. You assign to `var` in `var = ...`, but you only act upon your list. – Thierry Lathuille Jul 06 '21 at 10:07
  • 1
    You are able to *access both*. Note, if you did `listt += ['p']` you would get *the same error* – juanpa.arrivillaga Jul 06 '21 at 10:07
  • Python have a lot of weird behavior. For example, you can use variable declared after function. Sometimes you just have to live with it – JL0PD Jul 06 '21 at 10:07
  • 2
    @JL0PD no. No not at all. *Python doesn't have variable declarations*. The above behavior isn't strange or unexpected. – juanpa.arrivillaga Jul 06 '21 at 10:08
  • 1
    The *only* relevant detail here is that you are using an *assignment statement on `var`*. The *type of the object is irrelevant*. – juanpa.arrivillaga Jul 06 '21 at 10:09
  • @juanpa.arrivillaga, I beg to disagree. The question is why they don't get the error for `listt`. – buran Jul 06 '21 at 10:11
  • @buran regardless, you are wrong. See for yourself, use `listt += ['p']` *and you will get the same error*. The *types of the objects involved are irrelevant*. What is *relevant* is whether or not an *assignment* occurs to the *variable*, that is why you get a `UnboundLocalError` and not a `TypeError` or something else. – juanpa.arrivillaga Jul 06 '21 at 10:11
  • 2
    Kids, you're both right in your own ways. You *can mutate* a list, so you can change it from whatever scope. You *can't mutate* an int and hence must reassign it, which is where scope comes into play. – deceze Jul 06 '21 at 10:12
  • 1
    @deceze but that is a red herring. Again, the same issue would come up if you tried to re-assign the variable referencing the list (a very real example, `listt += ['p']`) The *type of object being referenced doesn't matter*. Similarly, I could *call a method on an int if I wanted to*. it would be rather pointless (or I could assign the result to another name) and the error won't come up. But saying that these scoping rules have anything to do with the types of objects involved is simply incorrect – juanpa.arrivillaga Jul 06 '21 at 10:14
  • Thanks guys! I understood it – Gathik Jindal Jul 06 '21 at 10:18

0 Answers0