Possible Duplicate:
Flatten (an irregular) list of lists in Python
While trying to flatten lists I run into infinite recursion if I pass strings. To my understanding this occurs as the first element of a string is again a string, which in turn can be iterated over. I solved this by seeing if my element quacks like a string, hence the second exception. This seems rather messy. Also, the real problem comes from the fact that strings have no 'base case' to their recursion. Are there other objects which have this property?
Does anyone have a cleaner solution?
def nestedsum(lst, init_sum):
for itm in lst:
try:
init_sum +=itm
except TypeError as e:
#check if we have some string iterator
# as this can cause infinite recurrsion
try:
itm + ''
except TypeError as e2:
init_sum +=nestedsum(itm)
else:
raise TypeError("Strings cannot be summed over")
return init_sum
Thanks in advance. Sorry if there is a similar post somewhere but I had no luck finding it.