cbbcbail
cbbcbail

Reputation: 1771

Passing a list between functions Python

If I make a list in one function, and edit it, then I want to be able to pass the finished list off to another function where it will be used to do more things.

def func1():
    numbers = [1, 2, 3, 4]
    if numbers.count(1) > 0:
        numbers.remove(1)
        func2()

def func2():
    two = numbers[0]

func1()

How could I get it so that it doesn't pull the error numbers not defined globally. I know why it is pulling the error, but after researching, I still can't find a good way to fix this problem.

Upvotes: 1

Views: 10886

Answers (2)

Abhijit
Abhijit

Reputation: 63707

Based on your mileage and requirement, choose one

  1. Pass the list as a parameter to the called function

    def func2(numbers):
        two = numbers[0]
    
    
    def func1():
        numbers = [1, 2, 3, 4]
        if numbers.count(1) > 0:
            numbers.remove(1)
            func2(numbers)
    
  2. Make both the functions part of a single Class and make the list an instance attribute

    class Foo(object):
        def __init__(self, numbers):
            self.numbers = numbers
            pass
        def func1(self):
            if self.numbers.count(1) > 0:
                self.numbers.remove(1)
                self.func2()
        def func2(self):
            two = self.numbers[0]
    
    
    Foo([1, 2, 3, 4]).func1()
    
  3. Redesign so that the called function is decorated with the caller

    def func1(func):
        def wraps(*argv):
            numbers = argv[0]
            if numbers.count(1) > 0:
            numbers.remove(1)
            func(*argv)
        return wraps
    
    @func1
    def func2(numbers):
        two = numbers[0]
    
    
    func2([1,2,3,4])
    
  4. Closure with nested function

    def func1():
        def func2():
            two = numbers[0]
        numbers = [1, 2, 3, 4]
        if numbers.count(1) > 0:
            numbers.remove(1)
            func2()
    
    
    func1()
    

Upvotes: 9

moooeeeep
moooeeeep

Reputation: 32502

You can pass it as a function argument:

def func1():
    numbers = [1, 2, 3, 4]
    if numbers.count(1) > 0:
        numbers.remove(1)
        func2(numbers)

def func2(numbers):
    two = numbers[0]

func1()

You could also define the function nested in the scope where the list is defined:

def func1():
    def func2():
        two = numbers[0]

    numbers = [1, 2, 3, 4]
    if numbers.count(1) > 0:
        numbers.remove(1)
        func2()

func1()

Upvotes: 5

Related Questions