Thursday, April 28, 2011

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?

From stackoverflow
  • 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))
    
    MHarris : Something exactly like that. Oh the shame.
  • 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)
    
    MHarris : Thanks! Unfortunately fn2 is a third party API and doesn't take varargs.

0 comments:

Post a Comment