0

My question is to create a function which iterates a list within a list, and have the code such that if I keep introducing another list within that list, it still iterates to return one list e.g flatten_list([5, [4, 3, 2,[1,2,3]], 1]) gives [5,4,3,2,1,2,3,1]

My attempt at the question:

def flatten_list(x):
    list1=[]
    
    for i in x:
        if type(i)==list:
            for j in i:
                list1.append(j)
        else:
            list1.append(i)
    return list1
    
    
flatten_list([5, [4, 3, 2,[1,2,3]], 1])

But this gives an Output of: [5, 4, 3, 2, [1, 2, 3], 1]

I'm quite new to coding and would appreciate a simple answer even if its quite long! I've looked at other stackoverflow questions similar to this however they use complex commands such as isinstance() or flatten() and they don't quite answer my specific question e.g. Iterate a list using recursion Recursively going through a list (python)

  • In addition to the answers below, I suggest taking a look at [more_itertools.collapse](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.collapse)'s [source code](https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/more.html#collapse). It does exactly what you want, but add several more checks so that it can collapse more than just lists of lists. In fact, it can collapse any iterable of iterables, and you can specify a "base type" (strings are iterables, but you might not want to treat them the same way that you'd treat a list of characters). – Stef Dec 11 '21 at 13:30
  • At the very least I recommend replacing `if type(i) == list` with `if isinstance(i, list)`, and looking at this answer to a related question: [In Python, how do I determine if an object is iterable?](https://stackoverflow.com/a/1952655/3080723) – Stef Dec 11 '21 at 13:32
  • @Stef appreciate the guidance and will definitely check those resources linked! – Aleks Angus Dec 11 '21 at 13:57

3 Answers3

0

Your code will work only for a list inside a list.

A better approach is using recursion for i,

Something like this,

def flatten_list(x):
    list1=[]
    
    for i in x:
        if type(i)==list:
            for j in flatten_list(i):
                list1.append(j)
        else:
            list1.append(i)
    return list1
Himanshu Kawale
  • 389
  • 2
  • 11
0

This can be done using recursion without introducing flatten or isinstance:

def flatten_list(x):
    output = []

    for e in x:
        if type(e) == list:
            output.extend(flatten_list(e))
        else:
            output.append(e)
    
    return output

===================================

print(flatten_list([5, [4, 3, 2,[1,2,3]], 1]))

[5, 4, 3, 2, 1, 2, 3, 1]
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
ljdyer
  • 1,946
  • 1
  • 3
  • 11
0
def flatten_list(x, result = None):
    tmp_result = []

    if result :
        tmp_result = result
    
    for elt in x:
        if type(elt) ==list:
            flatten_list(elt, tmp_result)
        else:
            tmp_result.append(elt)

    return tmp_result
print(flatten_list([5, [4, 3, 2,[1,2,3]], 1])) # Output : [5, 4, 3, 2, 1, 2, 3, 1]
script0
  • 387
  • 2
  • 12