Finding elements not in a list

前端 未结 10 797
一向
一向 2020-11-27 13:29

So heres my code:

item = [0,1,2,3,4,5,6,7,8,9]
z = []  # list of integers

for item in z:
    if item not in z:
        print item

z<

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 13:55

    Your code is not doing what I think you think it is doing. The line for item in z: will iterate through z, each time making item equal to one single element of z. The original item list is therefore overwritten before you've done anything with it.

    I think you want something like this:

    item = [0,1,2,3,4,5,6,7,8,9]
    
    for element in item:
        if element not in z:
            print element
    

    But you could easily do this like:

    [x for x in item if x not in z]
    

    or (if you don't mind losing duplicates of non-unique elements):

    set(item) - set(z)
    

提交回复
热议问题