1

How would you check if the inside of the list is also a list?

For example:

[[2,3]]

This is a list inside of a list. For my code, I need to check if the list1 index is a list, if it is, add it to a new list as individual indexes instead of a list.

list1 = [1, [[2, 3]], [4], 5]
list2 = []
for i in range(0, len(list1)):
    if (isinstance(list1[i],list)):
        list2.extend(list1[i])
    else:
        list2.append(list1[i])

print(list2)

This prints out [1, [2,3], 4, 5]

This shows that it does add the 4, since 4 was originally as a list. But it doesn't add the 2,3 to the list.

This is what I want it to print out:

[1,2,3,4,5]

This is what I've tried to check if there is a list inside a list but it doesn't work:

elif(isinstance(list1[i],list) and isinstance(list1[i][0],list)):
        list2.extend(list1[i][0])
  • `I need to check if the list1 index is a list` - List indexes are always integers, you are thinking of elements/values. – jordanm Feb 19 '20 at 19:52
  • it prints that because list1 at index 1 is [[2,3]]. change it to [2,3], to fix the problem. But if you want it to handle n-th dimemsional list then just use recursion – DontBe3Greedy Feb 19 '20 at 19:53

1 Answers1

1

Use a recursive function to flatten the list:

def flatten(lst):
    assert isinstance(lst, list)
    result = []
    for i in lst:
        if isinstance(i, list):
            result.extend(flatten(i))
        else:
            result.append(i)
    return result
filbranden
  • 8,522
  • 2
  • 16
  • 32