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
91.1k18 gold badges194 silver badges178 bronze badges
asked Jul 13, 2015 at 6:45
3
  • possible duplicate of How to check if a specific integer is in a list
    Tim
    Commented Jul 13, 2015 at 6: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 Commented Jul 13, 2015 at 6:51
  • If anyone the answer answered your question accept it or comment saying it did not work Commented Jul 13, 2015 at 12:16

4 Answers 4

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 .

answered Jul 13, 2015 at 6:46
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
answered Jul 13, 2015 at 6:46
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
answered Jul 13, 2015 at 7:12
0

Using set

>>> r = [5,7,2]
>>> for i in set(range(10))-set(r):
... print(i)
...
0
1
3
4
6
8
9
>>>
answered Jul 13, 2015 at 13:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.