EXAMPLE FUNCTION:
def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
I've been reviewing some python interview questions and it seems I'm missing out on something basic here. For the script/function above I would have originally expected to see the following output for the reasons stated in the comment:
list1 = [10] #because default is currently []
list2 = [123, []] #because not using function default of list
list3=[10, 'a'] #because function default list has had 10 appended
Instead, though, the result for for list1 is:
list1 = [10, 'a'] #I don't understand.
It seems I'm missing out on what happens to a variable when it's passed back from a function in memory, possibly? It seems as though list1 when passed back from the function is pointing the variable at the default function 'list' parameter in memory. Then, this default function 'list' parameter is altered with the calling of list3. Finally, when printing list1 and list3 values, they're pointing at the same variable in memory and thus print the same result? Am I way off here?
Think I answered my own question here...
When checking out the memory address of the variables I received the following:
print(hex(id(list1))) =
0x10b49a518
print(hex(id(list2))) =
0x10b49a758
print(hex(id(list3))) =
0x10b49a518
Could someone make sure I'm interpreting this correctly? Also, I'll leave this question open for anyone else that finds it via my horribly worded title XD