Reputation: 7906
For example:
mytuple = ("Hello","World")
def printstuff(one,two,three):
print one,two,three
printstuff(mytuple," How are you")
This naturally crashes out with a TypeError because I'm only giving it two arguments when it expects three.
Is there a simple way of effectively 'splitting' a tuple in a tider way than expanding everything? Like:
printstuff(mytuple[0],mytuple[1]," How are you")
Upvotes: 4
Views: 3057
Reputation: 1686
Actually, it is possible to do it without changing the order of the arguments. First you have to transform your string to a tuple, add it to your tuple mytuple
and then pass your larger tuple as argument.
printstuff(*(mytuple+(" How are you",)))
# With your example, it returns: "Hello World How are you"
Upvotes: 0
Reputation: 10897
mytuple = ("Hello","World")
def targs(tuple, *args):
return tuple + args
def printstuff(one,two,three):
print one,two,three
printstuff(*targs(mytuple, " How are you"))
Hello World How are you
Upvotes: 1
Reputation: 22149
Kinda,... you can do this:
>>> def fun(a, b, c):
... print(a, b, c)
...
>>> fun(*(1, 2), 3)
File "<stdin>", line 1
SyntaxError: only named arguments may follow *expression
>>> fun(*(1, 2), c=3)
1 2 3
As you can see, you can do what you want pretty much as long as you qualify any argument coming after it with its name.
Upvotes: 6
Reputation: 391846
Not without changing the argument ordering or switching to named parameters.
Here's the named parameters alternative.
printstuff( *mytuple, three=" How are you" )
Here's the switch-the-order alternative.
def printstuff( three, one, two ):
print one, two, three
printstuff( " How are you", *mytuple )
Which may be pretty terrible.
Upvotes: 4
Reputation: 8063
You could try:
def printstuff(*args):
print args
Another option is to use the new namedtuple collections type.
Upvotes: 0