Reputation: 9501
I have the code below where I change the globals. Most of what I have read has said to stay away from globals... In the example below I want to use "make_lists" then print it in "print_list" then clear the list. I use globals to do this, suggestions on how to avoid globals?
I know I could add this all in one function, but this is all part of a bigger function this is the only part I am having problems with. Thank in advance.
x_lst = []
def make_lists():
global x_lst
x_lst.append("Hello")
def print_list():
global x_lst
for i in x_lst:
print(i)
x_lst = []
def main():
make_lists()
print_list()
if __name__ =="__main__":
main()
Upvotes: 0
Views: 1227
Reputation: 12150
To avoid using global, you have to use the return
keyword in the function declaration to return a value, which will be your newly created list in our case. You also have to use arguments
in the function declaration, which are the placeholders of the values in the function. So the reason why you don't need the global value is because you are passing the list from one function to another.
def make_lists():
return ['Hello'] # Your are creating the list with a single value,
# and return it
def print_list(ls):
for i in ls: # You are iterating thru the list,
print(i) # which is the input of this function
def main():
print_list(make_lists()) # In your main function you call the make_list()
# which will return the newly created list, and
# pass it to print_list, which will iterate thru
# the list and prints your values out
if __name__ =="__main__":
main()
Upvotes: 2
Reputation: 314
Here's my simple suggestion, why not give the functions inputs. Passing in a list to print out instead of using a global variable is an easy alternative. If you're looking for a way to keep state for a particular scope, maybe try putting these functions in a class (in other words use OOP)
The problem with global variables is that when you declare 'x_lst' as global, it opens up "x_lst" to outside the function, which may not or be your intended goal.
Upvotes: 1
Reputation: 280251
def make_list():
return ['Hello']
def print_list(l):
for x in l:
print(x)
def main():
print_list(make_list())
Pass data into functions with arguments, and pass data out with return values.
Upvotes: 1
Reputation: 18127
I've made the minimal set of changes to your code that illustrate how to pass your list instead of using a global. Hope this helps clarify.
def make_lists(x_lst):
x_lst.append("Hello")
def print_list(x_lst):
for i in x_lst:
print(i)
def main():
x_lst = []
make_lists(x_lst)
print_list(x_lst)
if __name__ =="__main__":
main()
Upvotes: 0