Here's what you can do (this applies to strings, numbers, mixed containers and nested lists)
from collections import Iterable
def flatten(items):
"""Yield items from any nested iterable; see Reference."""
for f in items:
if isinstance(f, Iterable) and not isinstance(f, (str, bytes)):for sub_f in flatten(f):yield sub_f
else:yield f
If you are using Python 3 then, replace for sub_f in flatten(f): yield sub_f with yield from flatten(f)
Ex.
lst = [[2, 3, 4], [5, 6, 7], [8], [9, 0]]
list(flatten(lst)) # nested lists
# [2, 3, 4, 5, 6, 7, 8, 9, 0]
You can also use timeit module from standard library:
$ python -mtimeit -s'm=[[2,3,4],[5,6,7], [8], [9,0]*99' '[item for sublist in p for item in sublist]'
10000 loops, best of 3: 254 usec per loop
$ python -mtimeit -s'l=[[2,3,4],[5,6,7], [8], [9,0]]*99' 'sum(p, [])'
1000 loops, best of 3: 070 usec per loop
$ python -mtimeit -s'p=[[2,3,4],[5,6,7], [8], [9,0]]*99' 'reduce(lambda q,w: q+w,p)'
1000 loops, best of 3: 1.1 msec per loop
Happy Learning.