"unlist" a list

mmillikan at vfa.com mmillikan at vfa.com
Thu Jan 17 16:34:33 CET 2002


"Daniel Dittmar" <daniel.dittmar at sap.com> writes:

> > I use a funktion that is defined as foo(v1,v2,*args), i.e. it is
> > called as
> >   a = foo(v1,v2,opt1,opt2,opt3...)
> > (in fact in my case foo is Tkinter.OptionMenu)
> >
> > Unfortunately, I have the optional arguments in list
> >   options = [opt1,opt2,opt3,...]
> > and oviously foo(v1,v2,options) goes wrong since foo assumes that
> > opt1 is the list options.
> 
> use foo (v1, v2, *options)
> or (in older Pythons) apply (foo, (v1, v2) + tuple (options))
> 
> Daniel

The func(a,b,c,*more) spelling  doesn't work when the sequence to be unpacked is in 
any other position than last in the parameter list:

>>> zip(*seqseq,seq)
    File "<stdin>", line 1
     zip(*seqseq,seq)
                   ^
 SyntaxError: invalid syntax
 
 Could this syntax be extended to allow the splicing to happen at any
 position within the parameter list?
 
 In the interim, the code below  allows the construction:
 
 >>> zip(*splice(unnest(seqseq),seq))
 [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]
 
 More elaborate splicing also appears to work:
 
 >>> splice([10,20,30],[],unnest(['sam',unnest(unnest(['barney','fred']))]),seq,())
 [[10, 20, 30], [], 'sam', 'barney', 'fred', ('x', 'y', 'z'), ()]
 
 Only lightly tested, on 2.1.1
 
 Feedback on utility and/or horrible flaws appreciated
 
 ------------------------------------------------------------------

#splice3.py (python 2.1.x)
from __future__ import nested_scopes #not needed in 2.2

class unnest:
    '''A minimal wrapper for any sequence. When passed
    as an argument to the <splice> function the elements
    of the sequence will be spliced into the list returned
    replacing the <unnest> instance.'''
    
    def __init__(self,seq):
        if isinstance(seq,self.__class__):
            self.seq = seq.seq
        else: 
            for item in seq: break
            self.seq = seq
            
    def __getitem__(self,index):
        return self.seq[index]
        
    def __len__(self):
        return len(self.seq)

def splice(*args):
    '''Returns a list of its args with any instances
    of <unnest> replaced by the items of the unnests
    sequence attribute.'''
    
    def _splice(flat,*args): 
        for arg in args:
            if isinstance(arg,unnest):
                _splice(flat,*arg.seq)
            else:
                flat.append(arg)
        return flat
            
    return _splice([],*args)

Mark Millikan



More information about the Python-list mailing list