[BangPypers] Python List Comprehension Question
Anand Chitipothu
anandology at gmail.com
Thu Oct 2 12:57:31 CEST 2014
On Thu, Oct 2, 2014 at 3:51 PM, Rajiv Subramanian M <rajiv.m1991 at gmail.com>
wrote:
> Hello Group,
>
> I'm Rajiv working as web developer in bangalore.
>
> Objective:
> We need to convert the list containing integers and nested list of integer
> in it
> e.g.) x = [[1, 2, [3]], 4]
> into a flat list format
> e.g.) result = [1, 2, 3, 4]
>
> MyAnswer using Recursive function:
> def flat_it(List):
> result = []
> for item in List:
> if type(item) is int:
> result.append(item)
> else:
> result += flat_it(item)
> return result
> print flat_it(x)
>
> This actually works, but I tried to optimize this with List comprehension
> like the following code, but it never worked
>
> def flat_it(List):
> return [item if type(item) is int else flat_it(item) for item in List]
> print flat_it(x)
>
> This returns result without flatting like what i passed in argument [[1, 2,
> [3]], 4]
>
List comprehensions take a list and return a list of the same size (if you
don't use if condition).
What you have done is correct solution, though it could be slightly
improved like the following:
def flat_it(values, result=None):
if result is None:
result = []
for v in values:
if isinstance(v, list):
flat_it(v, result)
else:
result.append(v)
return result
Improvements:
* using isinstance is better than comparing type.
* avoids creation of intermediate lists by passing the result along the
recursive calls
Anand
More information about the BangPypers
mailing list