+ 2

how function works

Could someone explain how this code works? https://code.sololearn.com/cYmZ35pGe04t First time it prints [2] which is very clear but I expect that the second time when we call the function it prints the [5] but it will print [2, 5].

7th Mar 2018, 11:34 AM
rahim
rahim - avatar
4 ответов
+ 2
You use function with 1 positional parameter ('element' which is just a variable) and 1 keyword parameter ('to' which is a list). So first time you call it, you append '2' to 'to' list and return 'to' list which is then assign to 'myList', right? So, when you print it, output is 2. You already know it. Then you call the build function again. This time you also pass only positional argument to function which is '5' ,therefore 'to' list is untouched. Now, 'to' list already contained '2' right? It got '5' being appended. And you return 'to' list and assign to myOtherList. Finally, you print it , and output is [2,5] . That's it! PS: List type is mutable. So you can do modification to original list (in this case, you append values to list).
7th Mar 2018, 12:49 PM
Sylar
+ 2
Exactly! Just remember " replace-operation " return new value to you (Everytime). Eg. to = [] ; to = 5 This is replacing value of 'to' variable. 'to' get new value each time you use '='. In your code, you just use " inplace-operation " which is appending value to existing variable (which is list). Ofcourse, to modify, it must be mutable type (i.e list, set, dictionary, etc.) You can't modify immutable type (i.e str, int, float, tuple, etc.) Sorry if i am explaining which you already know.
7th Mar 2018, 1:27 PM
Sylar
+ 1
That code dosen't overwrite the entire list, it just appends your input to the end of it. That's why [2,5] is being output instead of only [5]. The '5' is being added as the next element in the list.
7th Mar 2018, 12:37 PM
apex137
apex137 - avatar
+ 1
Thanks a lot, I think the key point is if I do not pass keyword arg when I call the function this one remains what it was and do not set to an empty list as it does the first time. This concept is interesting and new to me
7th Mar 2018, 1:12 PM
rahim
rahim - avatar