Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function parameter: tuple/list

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.

like image 813
max Avatar asked Nov 17 '10 20:11

max


People also ask

How do you pass a tuple as a parameter in a function?

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.

How do you pass a tuple as parameter in Python?

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.

Can you pass a list as a parameter in Python?

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.

How do you pass a list of tuples in Python?

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.


1 Answers

If another_func just wants a iterable you can pass itertools.chain(x,'a') to it.

like image 199
Jochen Ritzel Avatar answered Sep 28 '22 00:09

Jochen Ritzel