What Is The Result Of The Below Lines Of Code?
def fast (items= ): items.append (1) return items print fast () print fast ()
I would say that there is no right or wrong with this code (except syntax errors). What the code *def fast (items= ):* is doing is called memoization, and is a type of caching data. As HonFu already mentioned the object items is created once and then used during the complete execution of the program. *items* will cache values that are returned from the function. So if you use *return 'hello'* instead of *return items* the string 'hello' is cached. The only problem by using memoization, is that it can happen by accident.
First of all, this code will cause a syntax error. Secondly, you shouldn't do like this, because items won't empty every time you run the function, it just will add 1 to items. Here, you can see it yourself: https://code.sololearn.com/ckzFjS7A11XT/?ref=app Here is working code: https://code.sololearn.com/cOOPuX5Fa9XV/?ref=app
the value for the default arg items is only created once, so the list will keep growing.
o.gak, tupel does not work because it is an immutable object, that means it can not be changed after creation. So after first initialization no further changes / assignments can be done.
Lothar It works for `list` and `dict`, but `tuple`. Do you have any idea about this?
second line means that your telling your computer to show the word fast
I’m a bit confused. Regardless of correctness of your syntax, we don’t give the funtion any parameter, shouldn’t it create a new list everytime? why just create once?
I don't think this counts as memoization - but I could be approaching it wrong. I added some additional calls to the "right code, did it like this" example, and that's not verifying the cached values from call to call. https://code.sololearn.com/cRq5mQ0377BH/?ref=app