sum and strings

Alex Martelli aleax at mac.com
Sun Aug 20 14:57:24 EDT 2006


Rhamphoryncus <rhamph at gmail.com> wrote:
   ...
> > > I believe the prefered method to flatten a list of lists is this:
> > >
> > > shallow = []
> > > for i in deep:
> > >     shallow.extend(i)
> > >
> > > Yes, it's three lines.  It's also very easy to read.  reduce() and
> > > sum() are not.
> >
> > I'd like to squeeze in the listcomp version, not because it is one line
> > shorter, but because I, and maybe others prefer short listcomps such as
> > the folowing:
> >
> > shallow = []
> > [shallow.extend(i) for i in deep]
> 
> I'm sure this has been mentioned before, but listcomps are for when you
> want to store the list and use it for further things, not for when you
> want a side effect.  TOOWTDI.
> 
> And of course, if saving a line was the reason:
> 
> shallow = []
> for i in deep: shallow.extend(i)

Another alternative equivalent to

  shallow = sum(deep, [])

but based on the "proper" usage of list comprehensions is

  shallow = [ item for sublist in deep for item in sublist ]


In terms of performance, however, the simple loop that you (rhamph)
posted is generally best -- e.g., with Python 2.5c1 on a MacbookPro:

brain:~/downloads alex$ python -mtimeit -s'deep=[range(9)]*9'
's=sum(deep,[])'
100000 loops, best of 3: 11.2 usec per loop

brain:~/downloads alex$ python -mtimeit -s'deep=[range(9)]*9' 's=[]
> for sublist in deep: s.extend(sublist)'
100000 loops, best of 3: 6.92 usec per loop

brain:~/downloads alex$ python -mtimeit -s'deep=[range(9)]*9' 's=[]
[s.extend(sublist) for sublist in deep]'
100000 loops, best of 3: 8.48 usec per loop

brain:~/downloads alex$ python -mtimeit -s'deep=[range(9)]*9' 's=[item
for sublist in deep for item in sublist]'
100000 loops, best of 3: 17.1 usec per loop


Alex



More information about the Python-list mailing list