1

I was working on an algorithm that 'flattens' a list, essentially removing any sublists within a list.

For example, [2, 3, [3, 4]] should become [2, 3, 3, 4]. I wrote the following to do this:

def flatten(l):
    total = []
    for i in l:
       if i == int:
           total.append(i)
       elif i == list:
           for j in i:
               total.append(j):
    return total

This algorithm yields an error, however. If someone could help that would be great. Also, if someone could show a recursive path to solve this problem so that lists of arbitrary 'depth' can be flattened (my current algorithm can only flatten a 2D array)

Yassine Faris
  • 951
  • 6
  • 26
user9873466
  • 95
  • 1
  • 5
  • This algorithm yields an error, however. If someone could help that would be great. Also, if someone could show a recursive path to solve this problem so that lists of arbitrary 'depth' can be flattened (my current algorithm can only flatten a 2D array) – user9873466 Jun 12 '18 at 15:38
  • 1
    Use `isinstance(i,int)`, if list append each, else append – 17slim Jun 12 '18 at 15:39
  • 1
    Use `isinstance` instead of `==`. – Arpit Kathuria Jun 12 '18 at 15:39
  • here's the answer: https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – keda Jun 12 '18 at 15:40
  • 1
    @keda that's not the answer, since this is not a list of lists. This just *has* some lists in it. – 17slim Jun 12 '18 at 15:41
  • 2
    Possible duplicate of [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – tourist Jun 12 '18 at 15:41
  • This is a duplicate: https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – anishtain4 Jun 12 '18 at 15:44
  • @anishtain4 read my above comment to keda. – 17slim Jun 12 '18 at 15:45
  • So the question looks exactly the same as this one: https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – anishtain4 Jun 12 '18 at 15:51

1 Answers1

2

There are two major issues here - first, you aren't checking the type of the item correctly (you should use isinstace) and second you aren't calling the function recursively:

def flatten(l):
    total = []
    for i in l:
       if isinstance(i, list):
           total.extend(flatten(i))       
       else:
           total.append(i)

    return total
Mureinik
  • 297,002
  • 52
  • 306
  • 350