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?
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.
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.
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.
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 !" )
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With