[Tutor] Another list comprehension question
John Fouhy
john at fouhy.net
Tue Feb 27 21:41:51 CET 2007
On 28/02/07, Smith, Jeff <jsmith at medplus.com> wrote:
> I realize however that this is probably much less efficient since you
> are iterating over the inner list rather than just taking it on in
> whole.
Well, you know what they say --- don't guess, profile :-)
Morpork:~ repton$ python -m timeit -s
'lsts=[["a","b","c"],["1","2","3"],["x","y","z"]]' 'flattened = [x for
l in lsts for x in l]'
100000 loops, best of 3: 3.9 usec per loop
Morpork:~ repton$ python -m timeit -s
'lsts=[["a","b","c"],["1","2","3"],["x","y","z"]]' 'flattened = []'
'for lst in lsts:' ' flattened.extend(lst)'
100000 loops, best of 3: 2.61 usec per loop
Hmm, interestingly, my claim that using .extend is more efficient
appears to be false, at least for this example:
Morpork:~ repton$ python -m timeit -s
'lsts=[["a","b","c"],["1","2","3"],["x","y","z"]]' 'flattened = []'
'for lst in lsts:' ' flattened = flattened + lst'
100000 loops, best of 3: 2.56 usec per loop
(not that there's much in it)
--
John.
More information about the Tutor
mailing list