#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    78
    Rep Power
    2

    Python "quirk" that has made me debug for hours.


    Why does this happen?
    In my head both prints should print out [1]

    is it because fsTest doesn't look for a global reference, and just declares local one, but fsTest2 cant find li in the local scope then goes upwards to change the one it finds in the global scope?

    Code:
    def fsTest(li):
        li = [5]
        return("done")
    
    def fsTest2(li):
        li[0] = 5
        return("done")
    
    li = [1]
    fsTest(li)
    print(li)
    
    li = [1]
    fsTest2(li)
    print(li)
    Last edited by leonnaley2; November 16th, 2013 at 04:28 AM.
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    The age-old reference confusion.

    The li parameter of your function has nothing to do with the top-level li variable. What you got there are two separate references. The only thing they have in common is that at the beginning of the function call, they both point to a same array. But when you reassign the li parameter, that doesn't affect the outer variable in any way. The two references now simply point to different arrays.

    It actually has nothing to do with functions. It's how variables in Python work. Try this, for example:

    python Code:
    x = [1]
    y = x       # y points to the same array as x, but it's a separate variable not "magically" bound to x
    y = [2]     # y now points to a different array
    print(x)    # ... but that doesn't affect x in any way
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65
    Remember a test print is your friend, so put them into your functions too.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    485
    Rep Power
    33
    You possibly want one of the two examples below
    Code:
    def fsTest(li):
        li[0] = 5
        return
    li = [1]
    fsTest(li)
    print(li)
    
    
    def fsTest2():
        li = [6]
        return li
    
    
    li=fsTest2()
    print(li)

IMN logo majestic logo threadwatch logo seochat tools logo