MHarris
MHarris

Reputation: 1821

Append a tuple to a list

Given a tuple (specifically, a functions varargs), I want to prepend a list containing one or more items, then call another function with the result as a list. So far, the best I've come up with is:

def fn(*args):
    l = ['foo', 'bar']
    l.extend(args)
    fn2(l)

Which, given Pythons usual terseness when it comes to this sort of thing, seems like it takes 2 more lines than it should. Is there a more pythonic way?

Upvotes: 2

Views: 3068

Answers (2)

Ned Batchelder
Ned Batchelder

Reputation: 376052

If your fn2 took varargs also, you wouldn't need to build the combined list:

def fn2(*l):
    print l

def fn(*args):
    fn2(1, 2, *args)

fn(10, 9, 8)

produces

(1, 2, 10, 9, 8)

Upvotes: 1

Brian
Brian

Reputation: 119371

You can convert the tuple to a list, which will allow you to concatenate it to the other list. ie:

def fn(*args):
    fn2(['foo', 'bar'] + list(args))

Upvotes: 9

Related Questions