0

I'm trying to figure out how to flatten a list of integers or strings. The lists contain nested lists and for example I want to flatten a list such as ["cat", "dog", ["animal", "human"]].

When using for loops my doctests do not always work, i.e. I get a decompostion of the "cat" and in my new list I have "c", "a", "t" added to the empty list I created and not the word "cat". for integers that are in a non nested list I also get an error saying 'int' object not iterable.

def flatten_lists(nested):
    '''(list) -> list
    For any nested list in a list, we want to form
    one single list containing all values of the list and sublist

    >>> flatten_lists([3, 4, 5, 6, 7])
    [3, 4, 5, 6, 7]
    >>> flatten_lists([[1]])
    [1]
    >>> flatten_lists(["cat", "dog", ["animal", "human"]])
    ["cat", "dog", "animal", "human"]
    '''
    flattened_list = []
    for sublist in nested:
        for item in sublist:
            flattened_list.append(item)
    return flattened_list

This code gives me the following errors for doctests 1 and 3 (the [[1]] works):

flatten_lists([3, 4, 5, 6, 7]):

TypeError: 'int' object is not iterable

flatten_lists(["cat", "dog", ["animal", "human"]])

Expected:

["cat", "dog", "animal", "human"]

Got:

['c', 'a', 't', 'd', 'o', 'g', 'animal', 'human']

Any help would be great thank you

Zeeshan
  • 1,078
  • 9
  • 14
  • just to give you an idea hwo to proced, go through each item in the main list , check if it's type is list or not, if it it list repeat process from this list else if it is not list then append or add this item to final list – sahasrara62 Nov 09 '19 at 17:52

1 Answers1

0

You can do it using recursion:

def flatten_lists(lst):
  result = []
  for elem in lst:
    if isinstance(elem, list):
      result = result + flatten_lists(elem)
    else:
      result.append(elem)
  return result

r = flatten_lists(["cat", "dog", ["animal", "human"]])
print(r)

This will return:

['cat', 'dog', 'animal', 'human']
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29