KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am trying to flatten lists recursively in Python. I have this code: def flatten(test_list): #define base case to exit recursive method if len(test_list) == 0: return [] elif isinstance(test_list,list) and type(test_list[0]) in [int,str]: return [test_list[0]] + flatten(test_list[1:]) elif isinstance(test_list,list) and isinstance(test_list[0],list): return test_list[0] + flatten(test_list[1:]) else: return flatten(test_list[1:]) I am looking for a very basic method to recursively flatten a list of varying depth that does not use any for loops either. My code does not pass these tests: flatten([[[[]]], [], [[]], [[], []]]) # empty multidimensional list flatten([[1], [2, 3], [4, [5, [6, [7, [8]]]]]]) # multiple nested list What is wrong with the code, and how can I fix it?
Tags (comma-separated)
Save Edits
Cancel