Get Count of function arguments passed in

David Lowry-Duda david at lowryduda.com
Wed Sep 11 12:19:30 EDT 2019


> I expected this to return 3 but it only returned 1.
> 
> matrix1 = [[1, -2], [-3, 4],]
> matrix2 = [[2, -1], [0, -1]]
> matrix3 = [[2, -1], [0, -1]]
> 
> def add(*matrix):
>     print(len(locals()))
>
> print(add(matrix1, matrix2))

In this case, locals will be a dictionary with exactly one key. The key 
will be "matrix", and its value will be a tuple of the two matrices 
matrix1 and matrix2. One solution (the wrong solution) to your problem 
would be to instead have

# Don't do this --- this is to illustrate what locals is doing
def add(*matrix):
    print(len(locals()['matrix']))

Now let's get to the right way to do this. Python stores the arguments 
specified by *matrix as a tuple of the name `matrix`. Of course, this is 
what locals what telling us, but there is no need to go through locals.

Instead, you can do

def add(*matrix):
    print(len(matrix))

and this will tell you how many arguments were passed in.

Good luck!

David Lowry-Duda



More information about the Python-list mailing list