0

I am trying to write the lambda based equivalent of Python functions as a learning exercise.

I have this working code, which takes a list and returns a new list with unique elements:

def unique_list(l):
    x = []
    for a in l:
        if a not in x:
            x.append(a)
    return x

When I test it, I get the expected result:

>>> print(unique_list([1,1,1,2,2,3,3]))
[1, 2, 3]

But my attempt at replacing this with lambda, as follows:

a = lambda l, x=[]:[x.append(a) for a in l if a not in x]

gives the wrong result:

>>> a([1,1,1,2,2,3,3]) 
[None, None, None]

What is wrong with the code?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sean
  • 1
  • 1
  • 5
    `list.append` returns `None`. – Ch3steR Jun 29 '22 at 04:38
  • Welcome to Stack Overflow. Aside from the linked duplicate, please note how I [edit]ed the question, as a model for how to ask clearly and concisely. – Karl Knechtel Jun 29 '22 at 04:42
  • As a side note: the problem doesn't actually have anything to do with `lambda`. You could just as easily reproduce the problem like `def a(l): x= []; return [x.append(a) for a in l if a not in x]`. Perhaps seeing it written this way makes the problem more clear. – Karl Knechtel Jun 29 '22 at 04:43
  • Also, for the specific task in this code, please also see https://stackoverflow.com/questions/480214. – Karl Knechtel Jun 29 '22 at 04:44

0 Answers0