On 7/12/19 5:53 AM, Shall, Sydney via Tutor wrote: > Thanks Mike, > > But I am still not clear. > > do I write: > > def f([x,y,z]) ? > How exactly do one write the function and how does one ensure that each > positional argument is accounted for.
The concept of packing will be useful, you can use the * operator to pack and unpack. A trivial example to get you started: >>> a = [1, 2, 3, 4] >>> print(a) [1, 2, 3, 4] >>> print(*a) 1 2 3 4 In the first print we print the list, in the second we print the result of unpacking the list - you see it's now four numbers rather than one list of four numbers. In a function definition you can pack with the * operator: >>> def f(*args): ... print(type(args)) ... print(len(args)) ... print(args) ... >>> >>> >>> f(1, 2, 3, 4) <class 'tuple'> 4 (1, 2, 3, 4) Here we called the function with four arguments, but it received those packed into the one argument args, which is a tuple of length 4. Python folk conventionally name the argument which packs the positional args that way - *args - but the name "args" has no magic, its familiarity just aids in recognition. By packing your positional args you don't error out if you're not called with the exact number you expect (or if you want to accept differing numbers of args), and then you can do what you need to with what you get. The same packing concept works for dictionaries as well, here the operator is **. >>> def fun(a, b, c): ... print(a, b, c) ... >>> d = {'a':2, 'b':4, 'c':10} >>> fun(**d) 2 4 10 What happened here is in unpacking, the keys in the dict are matched up with the names of the function parameters, and the values for those keys are passed as the parameters. If your dict doesn't match, it fails: >>> d = {'a':2, 'b':4, 'd':10} >>> fun(**d) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fun() got an unexpected keyword argument 'd' Dictionary unpacking looks like: >>> def fun(**kwargs): ... print(f"{kwargs}") ... >>> >>> fun(a=1, b=2, c=3) {'a': 1, 'b': 2, 'c': 3} again the name 'kwargs' is just convention. There are rules for how to mix regular positional args, unpacked positional args (or varargs), and keyword ares but don't want to go on forever here... _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor