1

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.

1
  • pass the list to func2 : func2(numbers). Commented Jan 19, 2013 at 19:30

2 Answers 2

9

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()
    
Sign up to request clarification or add additional context in comments.

1 Comment

Code please? Thanks. On how to put them both into a single class?
5

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.