A very basic answer, but should do what you're asking. Uses try
and except
to see if the item is iterable. If True, then recurse the function, if False, add the item to the list.
iterable = (((2,4),6,(9,(3,7))))
_list = []
def addToList(elem, listRef):
"""
elem: item you want to insert into the list
listRef: list you want to append stuff to
"""
try:
for x in elem:
addToList(x, listRef) # recursive call
except:
listRef.append(elem) # add the item if it's not iterable
# Main
for item in iterable:
addToList(item, _list) # iterate tuple, pass ea. element into addToList, pass the list you want to append to
print _list
Rule of thumb in Python, fail fast and fail cheap :)
Warning: If you have strings in the tuple, each char will be appended to _list
(since strings are iterable). I didn't design around strings because you didn't specify whether you use them or not.