4

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") 

6 Answers 6

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

Try the following:

printstuff(*(mytuple[0:2]+(" how are you",))) 

2 Comments

To match the arity in the original example.
But mytuple is already a 2-tuple. So you're slicing a 2-tuple (effectively copying it) for no apparent reason.
1
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 

Comments

0

You could try:

def printstuff(*args): print args 

Another option is to use the new namedtuple collections type.

1 Comment

But args would be (("hello","world)," how are you") as tuple and string.
0

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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.