+ 1

What Is The Result Of The Below Lines Of Code?

def fast (items= []): items.append (1) return items print fast () print fast ()

11th Nov 2019, 10:13 AM
Mohamed
Mohamed - avatar
11 Respostas
+ 10
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.
11th Nov 2019, 5:06 PM
Lothar
Lothar - avatar
+ 5
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
11th Nov 2019, 10:28 AM
Asman-H
Asman-H - avatar
+ 3
the value for the default arg items is only created once, so the list will keep growing.
11th Nov 2019, 10:28 AM
HonFu
HonFu - avatar
+ 3
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.
13th Nov 2019, 2:12 PM
Lothar
Lothar - avatar
+ 2
Lothar It works for `list` and `dict`, but `tuple`. Do you have any idea about this?
13th Nov 2019, 3:48 AM
o.gak
o.gak - avatar
+ 1
Thanks Asman-H
11th Nov 2019, 10:39 AM
Mohamed
Mohamed - avatar
+ 1
Lothar Thank you! mohamedy Now I think it is clear that what kind of data will be kept in momery. See the code below. Maybe can help you understand better. https://code.sololearn.com/ct7gpgkkRx7a/?ref=app
14th Nov 2019, 4:03 AM
o.gak
o.gak - avatar
0
second line means that your telling your computer to show the word fast
12th Nov 2019, 6:21 AM
Mohamed
0
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?
13th Nov 2019, 4:23 AM
sanzhang
sanzhang - avatar
0
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
13th Nov 2019, 5:14 AM
JoeSponge
JoeSponge - avatar
- 1
[1]
12th Nov 2019, 9:48 PM
Deepak Kumar Yadav
Deepak Kumar Yadav - avatar