-1
def flatten_lists(nested):
    '''
    >>> flatten_lists([[0], [1, 2], 3])
    [0, 1, 2, 3]
    '''
    list_of_lists = ([[0], [1, 2], 3])
    List_flat =  []
    for i in range(len(list_of_lists)): 
      for j in range (len(list_of_lists[i])): 
        List_flat.append(list_of_lists[i][j]) 
    return List_flat

I want to flatten the list [[0], [1, 2], 3] but I'm getting error:

TypeError: object of type 'int' has no len()

how to solve this

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • 1
    the last element, `3`, is not wrapped in a list constructor so when `i` is the last element, you're trying to take the length on a single integer, which is meaningless. Seems like you need to come up with some logic to test for whether a `len` exists – G. Anderson Nov 11 '19 at 23:12

1 Answers1

0

You're trying to treat every element of the outer list as though it is a list. The problem is that some elements in the inner list are not lists. A simple fix for your code in particular would be to wrap the inner for loop in a try/except block:

for i in range(len(list_of_lists)): 
    try:  # if the element is a list then add it
        for j in range (len(list_of_lists[i])): 
            List_flat.append(list_of_lists[i][j]) 
    except TypeError:  # so, if iteration fails, the element isn't a list
        List_Flat.append(list_of_lists[i])
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • The best way in python is what I'm doing here - try to iterate through it, and if it fails then it's not a sublist. Technically you could also check if the element has the necessary constructs for iteration (namely, an `__iter__()` method), but that's both confusing and can fail with custom datatypes. – Green Cloak Guy Nov 11 '19 at 23:24