0

is it possible to use the variable list from a function?

here is an example?
is it possible to call alist with its last used content?

def example(a):
    alist=[]
    alist.append(a)
    print alist

example(1)
print alist

thanks

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Gribouillis
1

The variables in a function's body are local to this function and can't be used outside the function. The solution is to return the variable and to catch the return value when the function is called

def example(a):
    alist=[]
    alist.append(a)
    print alist
    return alist # <---- return alist to the calling environment

thelist = example(1) # <----- we catch the returned list
print thelist

Note that we could have used the same name alist instead of thelist. I changed the
name to show that we are dealing with 2 different variables.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.