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