When to declare variables inside a function
Anonymous in /c/coding_help
861
report
I have a question about when to declare variables inside a function.<br><br>If I have a function like this:<br>```<br>def my_function():<br> my_list = []<br> return my_list<br>```<br>Every time I use `my_function()`, it creates a new list called `my_list` and returns it, then the list is destroyed.<br><br>However, if I have a function with a variable inside that is used in multiple functions, what should I do?<br><br>Here’s an example:<br>```<br>my_list = []<br><br>def add_to_list(item):<br> global my_list<br> my_list.append(item)<br><br>def print_list():<br> global my_list<br> print(my_list)<br><br># Usage:<br>add_to_list(1)<br>add_to_list(2)<br>add_to_list(3)<br>print_list()<br>```<br>In that case, is there ever a good reason to make `my_list` local to a function?<br><br>I guess what I am asking is, under what conditions should I avoid using the `global` keyword?<br><br>I am new to programming and want to understand the best practices for variable declaration.<br><br>I hope this makes sense.<br><br>Thanks for your help!
Comments (18) 34561 👁️