laura.neukamp
laura.neukamp

Reputation: 3

Python 3 - list comprehension "if not in list"

I have a list1 containing different integers. Now, I want to create a second list (list2), that contains all elements of list1 without doubles. And I want to create list2 with list comprehension, without the need of defining it first as an empty list:

list1 = [3,3,2,1,5,6,1,5,7]
list2 = [i for i in list1 if i not in list2]
print(list2)

That case would be perfect for set(), I know. But why it is not working with a list comprehension?

In these threads I found, that my list2-syntax should be fine:

Both top voted answers suggest a syntax like

[y for y in a if y not in b]

Upvotes: 0

Views: 3326

Answers (2)

Lewis Morris
Lewis Morris

Reputation: 2124

I'm not 100% sure but i believe the list isn't fully populated until the comprehension is complete.

You could simply do this if you were able to not use list comprehension

List(Set(list1))

Another option (not what you wanted either)

list1 = [3,3,2,1,5,6,1,5,7]
list2 = []
for itm in list1:
    if itm not in list2:
        list2.append(itm)

Upvotes: 0

sbw
sbw

Reputation: 46

It's because you're defining list2's contents self-referentially. While syntactically it's correct, semantically it's meaningless - list2 isn't defined yet when you refer to it in the filter/guard part of the list comprehension.

Upvotes: 1

Related Questions