On Thu, Oct 2, 2014 at 3:51 PM, Rajiv Subramanian M <rajiv.m1...@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 _______________________________________________ BangPypers mailing list BangPypers@python.org https://mail.python.org/mailman/listinfo/bangpypers