Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split list and pass them as separate parameter?

Tags:

python

list

My problem is I have values in a list. And I want to separate these values and send them as a separate parameter.

My code is:

def egg():
    return "egg"

def egg2(arg1, arg2):
    print arg1
    print arg2

argList = ["egg1", "egg2"]
arg = ', '.join(argList)

egg2(arg.split())

This line of code (egg2(arg.split())) does not work, but I wanted to know if it is possible to call some built-in function that will separated values from list and thus later we can send them as two different parameters. Similar to egg2(argList[0], argList[1]), but to be done dynamically, so that I do no have to type explicitly list arguments.

like image 487
Rohita Khatiwada Avatar asked Aug 02 '11 13:08

Rohita Khatiwada


People also ask

Can you pass a list as a parameter?

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 lists as parameters in Python?

In Python, we can easily expand the list, tuple, dictionary as well as we can pass each element to the function as arguments by the addition of * to list or tuple and ** to dictionary while calling function.

Can you use the split function with a list?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace.


3 Answers

>>> argList = ["egg1", "egg2"] >>> egg2(*argList) egg1 egg2 

You can use *args (arguments) and **kwargs (for keyword arguments) when calling a function. Have a look at this blog on how to use it properly.

like image 147
Jacob Avatar answered Sep 22 '22 22:09

Jacob


There is a special syntax for argument unpacking:

egg2(*argList)
like image 44
Sven Marnach Avatar answered Sep 19 '22 22:09

Sven Marnach


arg.split() does not split the list the way you want because the default separator does not match yours:

In [3]: arg
Out[3]: 'egg1, egg2'

In [4]: arg.split()
Out[4]: ['egg1,', 'egg2']

In [5]: arg.split(', ')
Out[5]: ['egg1', 'egg2']

From the docs (emphasis added):

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

like image 23
matt b Avatar answered Sep 22 '22 22:09

matt b