0

If I define a function 1 which takes as input a variable number of lists and provide as output one list as follows:

 def function1(*args):
    size = len(args)
    output = []    
    for k in range(size):
        do_something
        output.append(...)        
    return output  

and then a second function which also takes as input a variable number of lists (and return one list), which calls the first function as follows:

def function2(*args):
    size = len(args)
    output = []   
    for k in range(size):
            for index, line in enumerate(function1(args[k])):
                do_something  
    return output 

When I use the second function I got an error unless I define the 5th line of the code like this:

            for index, line in enumerate(function1(*args[k])):

My question is, should I also declare that the input number is undefined also when I call the function from another functin?

drSlump
  • 307
  • 4
  • 16
  • 1
    It's not entirely clear what's wrong, so maybe include the full traceback of your error. Did you mean to write `function1` in your "5th line of code" reference? As it is you switch it, and appear to be calling `function2` from within itself. Also, the `*` operator unpacks the list, so that the function inside `enumerate` is called with multiple arguments, instead of a single argument which is a list containing everything. – Jeff Oct 28 '16 at 15:41
  • I think we're going to need to see the actual code of `function1` to be of any help. Keep in mind that the function doesn't know where it's being called from (without some really janky hacks), so that isn't really a consideration. – Patrick Haugh Oct 28 '16 at 15:43
  • Yes actually there was a typo. I correctd the 5th line – drSlump Oct 28 '16 at 15:56
  • You should read about [*args and **kwargs](http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-parameters) – agg3l Oct 28 '16 at 16:00

1 Answers1

1

Consider these three examples, where all we change is the use of the * between two and three:

def fn1(*args):
    print(args)

In [1]: fn1('a', 'b', 1)

('a', 'b', 1)

def fn2(*args):
    fn1(args)

In [2]: fn2('a', 'b', 1)

(('a', 'b', 1),)

def fn3(*args):
    fn1(*args)

In [3]: fn3('a', 'b', 1)

('a', 'b', 1)

In the second one (fn2) where we didn't unpack args inside using an *, we got a tuple nested inside a tuple, which isn't what we wanted. Without seeing the full traceback I can't be sure this is your problem, but I suspect it's the case if it works after you modify the line as shown.

Jeff
  • 2,158
  • 1
  • 16
  • 29