简体   繁体   中英

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]

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM