+1

How to change a list declared in program from a function?

In my version of towers of Hanoi I wanted to initialize the list 'beg' in the beginning and change it in the hanoi function, but it creates a new list and the first beg list stays empty and never shows the input. When I initialize it with the range (what I do in the function) at the beginning then it works, but why? https://code.sololearn.com/cB7oOTGjozNK/?ref=app

3/22/2020 5:53:21 PM

Ditus

4 Answers

New Answer

+2

The problem is that you declare the global variable 'beg' at the start of your code but then, in your hanoi function, you re-declare it (actually you declare a new local variable whose scope is only within the function). If you say beg = ... that is a declaration of a variable. As lists are iterable, you are able to modify them within a function (you can do things like beg.append(...) for example), but declaring a new local variable means that that won't work. Inside your hanoi function, instead of your line beg = [x for x in range(n,0,-1)] you could do a for loop like this - for x in range (n,0,-1): beg.append(x) - that doesn't declare a new variable and should do what you're expexting it to do. Hope that helps and makes sense.

+1

Thank you both for explaining and tipps. WhyFry finally I know how that works, but I decided against it because then I have to remove the lists as parameters (because they cannot be both, global and parameters). And then you have to declare the lists although you don't use them outside the functions (little counter intuitive for me) Russ that worked pretty good in my interest. I used list comprehension because I think that had more style. See for yourself :) If you think other's could profit from my question consider upvoting ;)