-1
def flatten(data):
    list1=[]
    def flat(data):
        nonlocal list1
        
        if type(data)==list:
            for i in data:
                flat(i)
        else:
            list1.append(data)
    print(list1)

This is my code. I can't understand why the output of this function is always None. Besides, are there any method to renew the list at function?

my purpose: transform any list into flat-list.

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
고준호
  • 11
  • 2
  • 1
    you don't return anything, so the result of calling the functions are `None`. – thebjorn Jan 08 '23 at 13:07
  • 1
    `flatten` returns nothing (also known as `None`) and furthermore never calls the local function that it defines, so it doesn't really compute anything to return. – John Coleman Jan 08 '23 at 13:07
  • Please update your question with an example of how you call this function and deal with the result. Also, why does `flatten()` not call `flat()`? – quamrana Jan 08 '23 at 13:08
  • 2
    You never call `flat`, except from itself (but that never happens since there are no other calls to it). Look at what `flatten` does. It sets `list1` to `[]`. It defines a function that is never called. It prints `list1`, which is the empty list. Then it implicity returns `None`. Hint: A function has no effect unless it is called. Another hint: If a function doesn't explicitly return a value, it implicitly returns `None`. – Tom Karzes Jan 08 '23 at 13:09
  • 2
    Get another person or a plushie if none are available, and explain to them line for line what the code does. Not what you want it to do or what it's supposed to do, just explain what each line you've written does. – Cubic Jan 08 '23 at 13:12

2 Answers2

1

As said in the comments, that you don't return anything, so the result of calling function is None.

In your question you ask :

Besides, are there any method to renew the list at function?

Yes, you can flatten a 2D list with list comprehension:

[x for sublist in data for x in sublist]

there are many more ways.

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
1

From your code, one line is missing : the call to flat

def flatten(data):
    list1 = []

    def flat(data):
        nonlocal list1

        if isinstance(data, list): # better
            for i in data:
                flat(i)
        else:
            list1.append(data)

    flat(data) # <<<
    print(list1)

You can avoid the inner method with a method that returns something instead

def flatten(data):
    result = []
    for item in data:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

print(flatten([[1, 2, 3], 4, [[5, 6, 7]]]))  # [1, 2, 3, 4, 5, 6, 7]
print(flatten([[1, 2, 3], [[[4]]], [[5, 6, 7]]]))  # [1, 2, 3, 4, 5, 6, 7]
azro
  • 53,056
  • 7
  • 34
  • 70