I have written a program that eliminates the items in a list and outputs the other list.
Program :
r = [5,7,2]
for i in range(10):
if i != r:
print i
It outputs
0
1
2
3
4
5
6
7
8
9
But I want the desired output to be
0
1
3
4
6
8
9
What is the method to do so?
-
possible duplicate of How to check if a specific integer is in a list– TimCommented Jul 13, 2015 at 6:49
-
1Because i is an integer and r is a list. So, you are comparing int to a list. That's why it is every time coming as not equal and printing every integer as per your logic. So, use if i not in r– Tanmaya MeherCommented Jul 13, 2015 at 6:51
-
If anyone the answer answered your question accept it or comment saying it did not work– The6thSenseCommented Jul 13, 2015 at 12:16
4 Answers 4
When you do - i !=r
its always true, because an int
and a list
are never equal. You want to use the not in
operator -
r = [5,7,2]
for i in range(10):
if i not in r:
print i
From python documentation -
The operators
in
andnot in
test for collection membership.x in s
evaluates to true ifx
is a member of the collections
, and false otherwise.x not in s
returns the negation ofx in s
.
You are checking if a integer is not equal to to list
.which is right so it prints all the value
What you really wanted to do is check if the value is not available in the list .So you need to use not in
operator
r = [5,7,2]
for i in range(10):
if i not in r:
print i
You can try like this,
>>> r = [5, 7, 2]
>>> for ix in [item for item in range(10) if item not in r]:
... print ix
...
0
1
3
4
6
8
9
Using set
>>> r = [5,7,2]
>>> for i in set(range(10))-set(r):
... print(i)
...
0
1
3
4
6
8
9
>>>
Explore related questions
See similar questions with these tags.