-5

given a list

lt=[1,2,[3,[5,[6,[7]]]]] 

I know this is a basic question and I have done it with for loops but, I need to understand how this basic question can be done in a single or two lines. This was asked to me in an interview.

return [1,2,3,5,6,7]
CypherX
  • 7,019
  • 3
  • 25
  • 37
Ricky
  • 147
  • 1
  • 2
  • 9
  • 1
    Possible duplicate of [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – benvc Oct 15 '19 at 00:48
  • are you sure it's only two lines? With recursion you might do something with two lines, but then you had to call the declared function, which would be a third line. You see for example an answer from DarryG, but ut us using three lines and not two. two lines do ceclare the function and one to call it. – gelonida Oct 15 '19 at 00:50
  • 1
    @bencv: Yes in fact this is a duplicate. One of the solutions in https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists uses only two lines (or one with ';') It's Statham's answer. However reduce is no more a predeclared function in python3, so one had to add some imports to the line – gelonida Oct 15 '19 at 01:01

3 Answers3

1

This is a modified version of @DarrylG's solution, helping to get the line count down.

flatten = lambda lst: sum((flatten(v) if isinstance(v, list) else [v] for v in lst), [])
flatten(lt)

Lambda functions can be recursive, but are one line shorter then function declarations.

And this could also be in one line by using a ;

flatten = lambda lst: sum((flatten(v) if isinstance(v, list) else [v] for v in lst), []) ; flatten(lt) 
gelonida
  • 5,327
  • 2
  • 23
  • 41
1

Use a function to flatten recursively.

Solution

# Custom function
def get_flatlist(l, flat_list=None, no_more_list_elements = True):
    if flat_list is None:
        flat_list = list()

    for x in l:
        if isinstance(x,list):        
            flat_list += x
            no_more_list_elements = no_more_list_elements & False
        else:
            flat_list.append(x)
            no_more_list_elements = no_more_list_elements & True
    #print(no_more_list_elements)
    if not no_more_list_elements:        
        flat_list = get_flatlist(flat_list.copy(), 
                                 flat_list=None, 
                                 no_more_list_elements = True)
    return flat_list    

get_flatlist(lt)

Output:

[1, 2, 3, 5, 6, 7]

Data

lt=[1,2,[3,[5,[6,[7]]]]] 
CypherX
  • 7,019
  • 3
  • 25
  • 37
0

Method to flatten lists of lists (1-2 line function) (mod of Flatten an irregular list of lists)

  1. Use a generator to create single element lists
  2. Use sum to append these into a single list


def flatten(lst):
    return sum( ([x] if not isinstance(x, list) else flatten(x)
                 for x in lst), [] )

lt=[1,2,[3,[5,[6,[7]]]]]

print(flatten(lt))

Output
[1, 2, 3, 5, 6, 7]
DarrylG
  • 16,732
  • 2
  • 17
  • 23