0

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

5
  • 2
    append return none. try list comprehension : l = lambda m : [x for x in range(m)] Commented Dec 4, 2022 at 20:14
  • 2
    Why don't just use List Comp directly - lst = [x for x in range(10) ] Like ^^^ indicated append is in-place ops. Should not do that! Commented Dec 4, 2022 at 20:15
  • 1
    create_list = lambda limit : list(range(limit)) Commented Dec 4, 2022 at 20:17
  • 2
    Note that my_list is actually correctly filled (try printing it)! It's just that the output of your function ISN'T my_list . Commented Dec 4, 2022 at 20:19
  • No real need for a function for something like this since list(range(10)) is easy enough to type and clearer than using a lambda function to mutate a list. Commented Dec 4, 2022 at 20:25

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer.i'm trying to write it with lamba, is it possible to show me how to write this code using lambda and one line for loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.