Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
3 views
in Python by (3.9k points)
edited by

Is there any shortcut to make a simple list out of a complex one in python?

I already performed for a loop but searching for a one liner, when I try to reduce it, I got an error, given below for Ref.

Syntax:

l = [[2, 3, 4], [5, 6, 7], [8], [9, 0]]
reduce(lambda z, x: z.extend(x), l)

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'

Please help me with it.

2 Answers

0 votes
by (46k points)
edited by

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. 

0 votes
by (106k points)

You can use itertools.chain():

>>> import itertools

>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]

>>> merged = list(itertools.chain(*list2d))

You can use the following video tutorials to clear all your doubts:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

+1 vote
2 answers
+2 votes
3 answers
+3 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...