Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

my list accumulates previous values even after setting it to [ ] at the end of the recursive function

Y
YUSUPHA JUWARA (450 points)
0 6 10
in News by (450 points)
Hello everyone,

I know that lists are mutable. So, whenever I want them to start as empty lists, I set them to [ ]. For instance, if I am working with a list named my_list, and I want it to start anew at every new function  call, I do something like this: another_list = my_list[:], then I set my_list = [ ] and then return another_list. This has been working for me. However, today it doesn't work quite well. It accumulates the previous values together with the new values. Though when I call it with a directory name, it works well, but when I run the grade.py, I see that the first one is correct, then from there it accumulates the previous values and the current ones. For clarity, the error is relating to the ex4 of the simulation exam. If anyone wants to help and wants to see my code, please don't hesitate to let me know!. I am only and solely interested to know why this happens, and how to avoid similar one during exams. Is it the grade.py that does this, and if yes, how to solve it then?

Thanks to anyone wanting to help, and have a nice holiday!
239 views
closed

1 Answer

Best answer
angelo.spognardi (8190 points)
77 155 226
by (8.2k points)
selected by

Hi Yusupha, don't forget that when you assign a value to a variable in a function, that variable becomes local to the function itself. This implies that, when the name of the assigned variable is the same of that of a parameter received as input by the function, that variable will be a different one with respect to the one of the parameter given by the calling function. With respect to you problem, this means that when you set my_list = [], my_list *is no more* the same you received as a parameter and, then, the values in my_list will be the same it had when received. In order to really remove all the elements from a list you need to use the list methods that operate on that specific instance of list, like the clear method or the slicing operator. I suggest you to give another read to the python manual and to watch again our lectures that where specifically focused on lists.

All the best,

A.