Pass list items as arguments to method [duplicate] - python

This question already has answers here:
How to extract parameters from a list and pass them to a function call [duplicate]
(3 answers)
How to split list and pass them as separate parameter?
(4 answers)
Closed 1 year ago.
Assuming i have a method definition like this do_stuff(*arg).
I have a list of values, ['a','b',...]. How best can i pass the values of this list as individual arguments to the do_stuff method as do_stuff('a','b',...) ?
I've unsuccessfully tried using list comprehension - do_stuff([str(value) for value in some_list])
I am hoping i don't have to change do_stuff() to accept a list
Any pointers would be appreciated.

You can pass them using the "*" operator. So an example would be like this:
def multiplyfouritems(a,b,c,d):
return a*b*c*d
multiplyfouritems(*[1,2,3,4])

It's the same syntax, with the *:
do_stuff(*['a','b','c'])

Related

Trying to use multiple arguments for .append, anyway how? [duplicate]

This question already has answers here:
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Closed 4 years ago.
I am trying to append a set of objects combined into one as a single object on the end of a list. Is there any way I could achieve this?
I've tried using multiple arguments for .append and tried searching for other functions but I haven't found any so far.
yourCards = []
cards =["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
suits = ["Hearts","Diamonds","Clubs","Spades"]
yourCards.append(cards[random.randint(0,12)],"of",suits[random.randint(0,3)])
I expected the list to have a new element simply as "Two of Hearts" etc. but instead I recieve this error:
TypeError: append() takes exactly one argument (3 given)
You are sending append() multiple arguments not a string. Format the argument as a string as such. Also, random.choice() is a better approach than random.randint() here as stated by: #JaSON below.
3.6+ using f-strings
yourCards.append(f"{random.choice(cards)} of {random.choice(suites)}")
Using .format()
yourCards.append("{} of {}".format(random.choice(cards), random.choice(suites)))
string concatenation
yourCards.append(str(random.choice(cards)) + " of " + str(random.choice(suites)))
#You likely don't need the str() but it's just a precaution
Improving on Alex's join() approch
' of '.join([random.choice(cards), random.choice(suites)])
yourCards.append(' '.join([random.choice(cards), "of", random.choice(suits)]))

Python - Function argument with a comma [duplicate]

This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 4 years ago.
I want to have an argument in a function that fills an array with multiple strings, so that i have
def Test(colors):
colorarray = [colors]
which i can fill with
Test(red,blue)
but i always get either the takes 2 positional arguments but 3 were given error or the single strings do not get accepted (e.g. TurtleColor(Color[i]) tells me "bad color string: "red","blue")
i know i can pass the strings as seperate arguments, but i kind of want to avoid having that many different arguments.
You need to read input arguments as a list
def Test(*colors):
colorarray = [*colors]
print(colorarray)
Test('red','blue')

Python __dict__ conversion to kwargs [duplicate]

This question already has answers here:
Converting Python dict to kwargs?
(3 answers)
Closed 5 years ago.
I want to build a query for sunburnt(solr interface) using class inheritance and therefore adding key - value pairs together. The sunburnt interface takes keyword arguments. How can I transform a dict ({'type':'Event'}) into keyword arguments (type='Event')?
You can do this using dictionary unpacking:
dct = dict({'type':'Event'})
# equivalent to func(type='Event')
func(**dct)

How to pass a list as a function's arguments [duplicate]

This question already has answers here:
Expanding tuples into arguments
(5 answers)
Closed 8 months ago.
If I have a function:
def run(time, message, time_span_pattern):
...
And a list like:
run_args = ['1s', '1 second alarm', <_sre.SRE_Pattern object at 0x100435680>]
How can I pass the list, as separate arguments, to run? Is there a builtin way to do this, or am I forced to reference each element individually and by index?
You're looking for:
run(*run_args)
This is explained in more detail in this StackOverflow answer about the star and double star operator
It's also covered in the python docs

Input from List (Python) [duplicate]

This question already has answers here:
How to extract parameters from a list and pass them to a function call [duplicate]
(3 answers)
Closed 7 years ago.
I have a parameter list which is just inputs separated by commas.
Now that I have a non-empty list, myList[], how do I turn the entries of L into a parameter list?
Example: if want
myList[0], myList[1], myList[2]..., myList[10]
How can I do that? Thank you! Is there anything similar to unpacking?
You can use unpacking with *.
f(*myList)

Categories