I've been working to hone my understanding of recursion [and become a better programmer in general]. Today a wrote some code to flatten a tuple of tuples. The code is as follows:
def recursive_tuple_flatten(tuple_list):
if type(tuple_list) is tuple:
if type(tuple_list[0]) is tuple:
list_of_lists = [list(tuple_list[0]), tuple_list[1:]]
return recursive_tuple_flatten([i for j in list_of_lists for i in j])
else:
return recursive_tuple_flatten(list(tuple_list))
else:
if type(tuple_list[-1]) is tuple:
list_of_lists = [tuple_list[:-1], list(tuple_list[-1])]
return recursive_tuple_flatten([i for j in list_of_lists for i in j])
else:
return tuple_list
k = ((1,(2)),(3,(4,5)))
recursive_tuple_flatten(k)
The code works, but I'd really appreciate any advise and coaching to help me improve this code and make it more elegant. Have a great day!