L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2]
l2 = []
print([lambda x: l2.append(x) for x in L1 if x not in l2])
I am expecting the code should return the unique numbers in the list using list comprehension in python.
5
You’ve got several problems:
- You’re creating a
list
oflambda
functions, not calling any of them - If you fix this by changing to
print([l2.append(x) for x in L1 if x not in l2])
, it still won’t work as you expect, because you’ll be making and printing alist
ofNone
s (the return value oflist.append
).l2
will be modified as you expect, you just won’t see it. - If you split the work to:
[l2.append(x) for x in L1 if x not in l2] print(l2)
it will work, but it’s incredibly unPythonic. List comprehensions are a functional construct; they should receive an input iterable, produce an output
list
, and otherwise be entirely self-contained. Using them for side-effects, and especially using them primarily/only for side-effects, is counter-intuitive in the extreme.
If you want your current design, use a normal for
loop, not a listcomp:
L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2]
l2 = []
for x in L1:
if x not in l2:
l2.append(x)
print(l2)
But modern Python can actually do exactly what you’re doing far more efficiently, because as of 3.6 (3.7 as a language guarantee) dict
s are insertion-ordered, so rather than the O(n²)
cost paid above, you can just do:
L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2]
l2 = list(dict.fromkeys(L1))
print(l2)
creating a temporary dict
(in O(n)
time) to uniquify while preserving order, then creating a list
from the dict
s keys (another O(n)
step, but even cheaper than the dict
creation).
1
idealy you can use set
or dict.fromkeys
like this:
l2 = list(dict.fromkeys(L1))
# OR
l2 = list(set(L1))
Full Example
4
The issue is that you’re creating a list of lambdas rather than executing them. Try this instead:
L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2]
l2 = []
[l2.append(x) for x in L1 if x not in l2]
print(l2)
This will give you the unique numbers in L1.