0

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?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Rajath
  • 1,306
  • 2
  • 10
  • 18
  • possible duplicate of [How to check if a specific integer is in a list](http://stackoverflow.com/questions/14608015/how-to-check-if-a-specific-integer-is-in-a-list) – Tim Jul 13 '15 at 06:49
  • 1
    Because **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 Meher Jul 13 '15 at 06:51
  • If anyone the answer answered your question accept it or comment saying it did not work – The6thSense Jul 13 '15 at 12:16

4 Answers4

3

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 and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s .

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2

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
The6thSense
  • 8,103
  • 8
  • 31
  • 65
0

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
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
0

Using set

>>> r = [5,7,2]
>>> for i in set(range(10))-set(r):
...     print(i)
...
0
1
3
4
6
8
9
>>>
shantanoo
  • 3,617
  • 1
  • 24
  • 37