My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple:
def func(arg): # arg is tuple or list
another_func(x)
# do other stuff here
Now I need to modify the function slightly, to process an additional element:
def func(arg): #arg is tuple or list
another_func(x + ['a'])
# etc
Unfortunately this is not going to work: if arg is tuple, I must say x + ('a',)
.
Obviously, I can make it work by coercing arg to list. But it isn't neat.
Is there a better way of doing that? I can't force callers to always pass a tuple, of course, since it simply shifts to work to them.
There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. This is useful when taking variable number of arguments in the function. Due to the * prefix on the args variable, all extra arguments passed to the function are stored in args as a tuple.
Example: Pass a Tuple as an Argument using *args Syntax Unpacking in Python uses *args syntax. As functions can take an arbitrary number of arguments, we use the unpacking operator * to unpack the single argument into multiple arguments. This is a special way of receiving parameters to a function as a tuple.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
If another_func
just wants a iterable you can pass itertools.chain(x,'a')
to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With