1

I know this has been asked before but I don't see any solutions for when there is a list of the type:

original_list = [[1,2], [3], [4,5,[6]]]

Tried this method:

def flatten(list):

    """Given a list that contains elements and other lists, this
       will return a new list that has no sublists ("flattened")"""

    flat = [] # new empty list to populate with flattened list

    for sublist in list: # iterate through list elements
        for element in sublist: #
            flat.append(element)

    return flat

print(flatten([1,2,3]))

This method too:

old_list = [[1,2], [3], [4,5,[6]]]

flat1 = []

flat1 = [sum(old_list, [])] # 1 layer deep

flat2 = []

flat2 = [sum(flat1), []] # 2 layers deep

print(sort2)

Not having any luck... tips? Thanks!

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
astrae
  • 63
  • 6
  • 3
    It is impossible for you to be the first one to have this problem. Please do your research before posting a question. There is already a question with 3392 upvotes and 40 answers. – Harshal Parekh Jun 11 '20 at 23:51
  • 1
    @ggorlen The duplicate link you've put, is not valid for this question. Please check again. – Mayank Porwal Jun 11 '20 at 23:51
  • 2
    @MayankPorwal please explain why not? There are solutions in that post for *n* depth as well. – Harshal Parekh Jun 11 '20 at 23:55
  • 1
    @HarshalParekh I missed the n-depth solutions. They are at the bottom. I just checked the above solutions. Got it. – Mayank Porwal Jun 11 '20 at 23:57
  • @MayankPorwal The link has dozens and dozens of approaches, benchmarks and list flattening algorithms using any package for any depth you might need. It's the canonical answer, this is a clear dupe and there's no need for this question to exist as it only adds more noise and indirection for people trying to find that thread. – ggorlen Jun 12 '20 at 00:32

4 Answers4

2

Something along these lines?

In [6]: original_list = [[1,2], [3], [4,5,[6]]]                                                                                                                         

In [7]: def flatten(potential_list): 
   ...:     new_list = [] 
   ...:     for e in potential_list: 
   ...:         if isinstance(e, list): 
   ...:             new_list.extend(flatten(e)) 
   ...:         else: 
   ...:             new_list.append(e) 
   ...:     return new_list 
   ...:                                                                                                                                                                 

In [8]: flatten(original_list)                                                                                                                                          
Out[8]: [1, 2, 3, 4, 5, 6]
MPall
  • 63
  • 1
  • 6
1

You can use Collections.Iterable:

In [2810]: def flatten(x): 
      ...:     if isinstance(x, collections.Iterable): 
      ...:         return [a for i in x for a in flatten(i)] 
      ...:     else: 
      ...:         return [x] 
      ...: 

In [2811]: flatten(original_list)
Out[2811]: [1, 2, 3, 4, 5, 6]

OR brute force like this:

In [2803]: flat_list = [] 
      ...: for sublist in original_list:
      ...:     for item in sublist: 
      ...:         if isinstance(item,list): 
      ...:             for sub_item in item: 
      ...:                 flat_list.append(sub_item) 
      ...:         else: 
      ...:             flat_list.append(item)

In [2804]: flat_list 
Out[2804]: [1, 2, 3, 4, 5, 6]
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
1

If you have nested-nested lists, the best way to flatten is using generator function

original_list = [[1,2], [3], [4,5,[6]]]

def flatten(l):
    for i in l:
        if isinstance(i,list):
            yield from flatten(i)
        else:
            yield i

list(flatten(original_list))
#[1, 2, 3, 4, 5, 6]
Transhuman
  • 3,527
  • 1
  • 9
  • 15
1

Here's a recursive solution:

def recursive_flatten(lst, retlist = []):
    for item in lst:
        if type(item) is int:
            retlist.append(item)
        else:
            recursive_flatten(item, retlist)
    return(retlist)
David
  • 424
  • 3
  • 16