views:

113

answers:

8

So heres my code:

item = [0,1,2,3,4,5,6,7,8,9]

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

Z contains a list of integers. I want to compare item to Z and print out the numbers that are not in Z when compared to item. I can print the elemtens that are in Z when compared not items, but when i try and do the opposite using the code above nothing prints.

Any help?

+1  A: 
list1 = [1,2,3,4]; list2 = [0,3,3,6]

print set(list2) - set(list1)
jspcal
+9  A: 
>> items = [1,2,3,4]
>> Z = [3,4,5,6]

>> print list(set(items)-set(Z))
[1, 2]
Antony Hatchkins
+1  A: 
>>> item = set([0,1,2,3,4,5,6,7,8,9])
>>> z = set([2,3,4])
>>> print item - z
set([0, 1, 5, 6, 7, 8, 9])
sberry2A
+2  A: 

If you run a loop taking items from z, how do you expect them not to be in z? IMHO it would make more sense comparing items from a different list to z.

Doc Brown
+6  A: 

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:

set(item) - set(z)
ezod
Thank you for you help :)
Dave
A more Pythonic way of writing that first bit would be `[x for x in item if x not in z]`
BlueRaja - Danny Pflughoeft
+1  A: 

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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

As has been stated in other answers, you may want to try using sets.

ntownsend
A: 

Your code is a no-op. By the definition of the loop, "item" has to be in Z. A "For ... in" loop in Python means "Loop though the list called 'z', each time you loop, give me the next item in the list, and call it 'item'"

http://docs.python.org/tutorial/controlflow.html#for-statements

I think your confusion arises from the fact that you're using the variable name "item" twice, to mean two different things.

Josh Wright
A: 

You are reassigning item to the values in z as you iterate through z. So the first time in your for loop, item = 0, next item = 1, etc... You are never checking one list against the other.

To do it very explicitly:

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