Reputation: 1326
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?
Upvotes: 0
Views: 174
Reputation: 3705
Using set
>>> r = [5,7,2]
>>> for i in set(range(10))-set(r):
... print(i)
...
0
1
3
4
6
8
9
>>>
Upvotes: 0
Reputation: 21446
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
Upvotes: 0
Reputation: 90889
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
.
Upvotes: 3
Reputation: 8335
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
Upvotes: 2