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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
>>> 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.
Method 2
There is a special syntax for argument unpacking:
egg2(*argList)
Method 3
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.
Method 4
There are maybe better ways, but you can do:
argList = ["egg1", "egg2"] (a, b) = tuple(argList) egg2(a, b)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0