Some observations:
- function can return three different datatypes: None, int and str. Whatever usage follows, it must be very defensive (None if empty list, int if list with one integer, string as expected result)
- for me personally it's more natural to return only one datatype. In case of empty list it should be empty string
- it works only when elements are strings, otherwise TypeError will be raised
It's of course upon specific needs but nevertheless I would have solved this problem differently. I would have separated flattening the list and manipulating list elements.
I would have created stream of elements of flattened list:
This returns generator object which is memory efficient. It preserves all elements in their original type (which is often needed).
Now I can manipulate this stream whatever way I want:
- function can return three different datatypes: None, int and str. Whatever usage follows, it must be very defensive (None if empty list, int if list with one integer, string as expected result)
- for me personally it's more natural to return only one datatype. In case of empty list it should be empty string
- it works only when elements are strings, otherwise TypeError will be raised
It's of course upon specific needs but nevertheless I would have solved this problem differently. I would have separated flattening the list and manipulating list elements.
I would have created stream of elements of flattened list:
def flat_stream(lst): for item in lst: if isinstance(item, (list, tuple)): yield from flat_stream(item) else: yield item
This returns generator object which is memory efficient. It preserves all elements in their original type (which is often needed).
Now I can manipulate this stream whatever way I want:
>>> ls = ["a",["b","6"],"e",["5",["g","h"]],"i",["k"]] >>> ''.join(el for el in flat_stream(ls)) 'ab6e5ghik' >>> list(flat_stream(ls)) ['a', 'b', '6', 'e', '5', 'g', 'h', 'i', 'k']If there are different types of elements and I want to manage them differently (data often needs verifying, cleansing etc) then I can do it:
>>> ls = ["a",("b","6"),"e",[5,["g","h"]],"i",["k"]] # there is int and tuple in list >>> ''.join(str(el) for el in flat_stream(ls)) # convert all elements to str 'ab6e5ghik' >>> ''.join(el for el in flat_stream(ls) if isinstance(el, str)) # ignore int 'ab6eghik' >>> [el for el in flat_stream(ls) if not isinstance(el, str)] # ignore strings [5]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.