Hello, I have just read an example of a bad use of python variables; it would seem that this is quite important concept to grasp, but I can't yet "see" what is going on here ... def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list Can any one help, I would be most grateful.
Hope this should help you ... Jus have a look at it. http://stackoverflow.com/questions/12197966/parameter-value-correctness
u still need help ?
It's because this user tried to initialize an array as a parameter for the definition. You are supposed to initialize/declare your variable before you want to use it in the function as a paramater. I don't even think you can do this, but an example of a good append would be: list = [] //notice list is initialized BEFORE writing a function that will use list. def good_append(new_item, list) list.append(new_item) return list
Hello there, Thanks for your help; I have an idea forming as to why this is so now, I think these thoughts will consolidate with a little more experience; I am still learning the ropes and I having only previous experience with databases; this seems to make sense now. In fact whilst writing this I think the penny has dropped: def defines a function, so we don't want to ascribe that to any particular instance within any list that we are making or we will tie a knot between the object and its content ... Thanks again.
You're close. Most languages pass non-primitive data types( primitives are int, float, char, boolean ) like lists and objects by reference. In other words, when you call a function with my_list and an integer and the function appends to the list and increments the integer and then returns, and the calling function then prints the list and the int, the list has the append because it was passed by a reference to the original list, but the integer will be the same value because it is a primitive and is passed by copy. Here's a quick example of pass by copy: >>> def inc( foo ): ... foo += 1 ... >>> bar = 2 >>> inc( bar ) >>> bar 2
Here's a full example: ``` >>> def inc( foo, bar ): ... foo.append( "foo" ) ... bar += 1 ... >>> foo = [] >>> bar = 2 >>> foo [] >>> bar 2 >>> inc( foo, bar ) >>> foo ['foo'] >>> bar 2 ```
Oh sorry just saw your new post, let me see if I can find the head and the tail. Thanks for your help.
Join our real-time social learning platform and learn together with your friends!