1

I am trying to flatten a python3 list that has nan in it and it is causing an error.

The code I am using to flatten the list is

def flatten(x):
    if isinstance(x, collections.Iterable):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]

from Flatten (an irregular) list of lists. It works great for lists like [1,[123,132], 1] but it doesn't work on my list [nan, ['fiction', 'flash', 'short-story'], nan, nan, nan] The nans come from empty spaces in the pandas DataFrame.

I get the error RuntimeError: maximum recursion depth exceeded in cmp

Simon
  • 591
  • 1
  • 7
  • 17
  • 4
    If you're sure, your values will be lists, you could use `def flatten(x) return [a for i in x for a in flatten(i)] if isinstance(x, list) else [x]`? – Zero Jul 25 '17 at 17:10
  • 3
    The problem is not nans but the strings. `isinstance('str', collections.Iterable)` returns True. John's suggestion would solve that. – ayhan Jul 25 '17 at 17:11
  • @JohnGalt yes that worked. Thank you. – Simon Jul 25 '17 at 17:26

0 Answers0