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")
Bolster
  • 7,460
  • 13
  • 61
  • 96

6 Answers6

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.

Skurmedel
  • 21,515
  • 5
  • 53
  • 66
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.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
3

Try the following:

printstuff(*(mytuple[0:2]+(" how are you",)))
yan
  • 20,644
  • 3
  • 38
  • 48
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
Derek Litz
  • 10,529
  • 7
  • 43
  • 53
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"
Nuageux
  • 1,668
  • 1
  • 17
  • 29
0

You could try:

def printstuff(*args):
    print args

Another option is to use the new namedtuple collections type.

rlotun
  • 7,897
  • 4
  • 28
  • 23