A query about list

Tony Clarke a.clarke11 at ntlworld.com
Sun Oct 12 04:39:49 EDT 2003


"Robert Brewer" <fumanchu at amor.org> wrote in message news:<mailman.1065733220.31901.python-list at python.org>...
> Dave Benjamin wrote:
> > Santanu Chatterjee wrote:
> > > I am very new to python. I have a query about 
> > > list in python.
> > > 
> > > Suppose I have a list 
> > > a = [1,[2,3,4],5,6,7,[8,9,10],11,12]
> > > I want to know if there is any simple python
> > > facility available that would expand the above list
> > > to give
> > > a = [1,2,3,4,5,6,7,8,9,10,11,12]
> > > 
> > Normally, I'd suggest "reduce(operator.add, ...)" to flatten 
> > a list, but
> > since you've got some "naked" entries, that won't work...
> > 
> > >>> def merge(x, y):
> > ...     if type(y) is type([]): return x + y
> > ...     return x + [y]
> > ...
> > >>> reduce(merge, a, [])
> > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> > 
> 
> Neat trick with the third parameter to reduce! Didn't know about that
> behavior. That cuts my long one-liner down from:
> 
> >>> reduce(lambda x, y: {type([]): x}.get(type(x), [x]) + {type([]):
> y}.get(type(y), [y]), a)
> 
> to just:
> 
> >>> reduce(lambda x, y: x + {type([]): y}.get(type(y), [y]), a, [])
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> 
> /shudder. But it's fun. :)
> 
> 
> Robert Brewer
> MIS
> Amor Ministries
> fumanchu at amor.org



How about this single function (although not a single line:<), which
also works for any kind of sequence, and can cope with different types
in the sequence:

a = [1,[2,3,4],5,6,7,[8,9,10],11,12]

def depth(sequence):
  for item in sequence: 
   try:
     b=len(item) 
     depth(item)
   except:
    print item,
    continue
   
depth(a)

I think this is a precursor to generators, but I'm still on Python
2.1.




More information about the Python-list mailing list