-1

Im trying to flatten out the following list in python code. I keep running into an 'int is not iterable error' i know this is due to the list being both strings and ints. how do i account for this? sorry guys, first month of coding..... i know this is basic.

list_1 = [1,2,[3,[4,5],6],7,8,['hardware'],[['software'], 'interface']]


def flatten (list):
    flat = []
    for sublist in list_1:
        for item in sublist:
            flat.append(item)

    print(flat)
    return


flatten(list_1)
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
mhsmustang1
  • 113
  • 1
  • 1
  • 4
  • If you search on the phrase "Python flatten list", you’ll find resources that can explain it much better than we can in an answer here. Your problem is not the mixed types; rather, it's that you try to flatten things that are not lists. – Prune Mar 13 '19 at 20:35

1 Answers1

0

You should check that each item is a list before trying to flatten it.

def flatten(list_):
    flat = []
    for item in list_:
        if isinstance(item, list):
            flat.extend(flatten(item))
        else:
            flat.append(item)
    return flat
chepner
  • 497,756
  • 71
  • 530
  • 681