Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding elements not in a list

Tags:

python

list

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 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 elements that are in z when compared not item, but when I try and do the opposite using the code above nothing prints.

Any help?

like image 443
Dave Avatar asked Jan 20 '10 19:01

Dave


People also ask

How do you find elements that are not in lists?

To find the elements in one list that are not in the other: Use the set() class to convert the first list to a set object. Use the difference() method to get the elements in the set that are not in the list.

How do you check if a string is not in a list?

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list.

How do you check if an integer is not in a list in Python?

count() to check if the list contains. Another built-in method in Python, count() returns the number of times the passed element occurs in the list. If the element is not there in the list then the count() will return 0. If it returns a positive integer greater than 0, it means the list contains the element.

How do you check if it is list or not in Python?

Given an object, the task is to check whether the object is list or not. if isinstance (ini_list1, list ): print ( "your object is a list !" )


1 Answers

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) 
like image 68
ezod Avatar answered Nov 15 '22 22:11

ezod