Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a list from one function, inside another function python

I am new to python. This might be a simple question, but if I have many functions that are dependent on each other how would I access lists from one function to use in another.

So...

def function_1():
    list_1=[]

def function_2():
    list_2= [2*x for x in list_1]

def function_3():
    list_3= [x * y for x, y in zip(list_1, list_2)]

That is not the exact code but that is the idea of my problem. I would just put them all together in one function but I need them to be separate.

like image 656
user3469844 Avatar asked Aug 26 '26 19:08

user3469844


1 Answers

The correct way to do this would be to use a class. A class is an object that has internal variables (in your case, the three lists), and methods (functions that can access the internal methods). So, this would be:

class Foo(object):
    def __init__(self, data=None):
        self.list_1 = data if not data is None else []

    def function_2():
        self.list_2 = [2 * x for x in self.list_1]

And so on. For calling it:

foo = Foo()  # list_1 is empty
foo2 = Foo([1,2,3]) # list_1 is not empty
foo2.function_2()   
print foo2.list_2
# prints [2, 4, 6]
like image 155
Davidmh Avatar answered Aug 28 '26 10:08

Davidmh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!