Skip to content Skip to sidebar Skip to footer

Why Can I Not Call This Function Using A Variable As An Argument In Python?

Example: def somerando(a,b,c,d): if not a+b+c+d == 9000: return (a+b+c+d) somerando(1,2,3,4) Returns: 10 but randonumbs = [1,2,3,4] somerando(randonumbs) Gives the

Solution 1:

your function expects 4 arguments. randonumbs = [1,2,3,4] is a list (of four items); that is one argument for your function.

you could do this:

randonumbs = [1,2,3,4]
somerando(*randonumbs)

this usage of the asterisk (*) is discussed in this question or in PEP 3132.

Solution 2:

You passed randonumbs as list, means this whole list is considered as first argument to the function somerando You can use somerando(*randonumbs) . Here, * means pass as tuple & ** means pass as dictionary (key, value pair) if you use ** in function parameters/ arguments.

Thank you.

Solution 3:

The single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions, like below

randonumbs = [1,2,3,4]
somerando(*randonumbs)

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function.

randonumbs = {'a':1, 'b':2, 'c': 3, 'd': 4}
somerando(**randonumbs)

Post a Comment for "Why Can I Not Call This Function Using A Variable As An Argument In Python?"