Search code examples
pythonlambda

lambda function returning a list of None elements


does anyone know why the function fill the list with "None"? I can not find the problem, everything looks true.

my_lis = []
l = lambda m : [my_lis.append(x) for x in range(m)]
l(10) 

output : [None, None, None, None, None, None, None, None, None, None] 


if i print the x instead of append, i get 1 to 10 and the None list at the end. anyway I'm trying to get a list of numbers by this way


Solution

  • A simple list comprehension

    lst = [i**2 for i in range(3)]
    

    is interpreted as:

    lst = []
    for i in range(3):
        lst.append(i**2)
    

    Now back to your example: So your code is currently like this:

    my_lis = []
    
    def l(m):
        result = []
        for x in range(m):
            result.append(my_lis.append(x))
        return result
    
    
    print(l(10))  # [None, None, None, None, None, None, None, None, None, None]
    print(my_lis) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    So basically you're filling the my_lis when you call my_lis.append(), but .append() is an in-place method, It just adds item to the list but its return value is None and you're filling result with Nones. Indeed result is the what list comprehension hands you after-all.


    As per request in comment:

    You basically don't need extra my_lis list. The list comprehension inside the lambda gives you the final result, so:

    l = lambda m: [x for x in range(m)]
    print(l(10))
    

    Now [x for x in range(m)] is pointless and slower here, You can directly call list on range(m):

    l = lambda m: list(range(m))
    print(l(10))