Rajath
Rajath

Reputation: 1326

Python If statement : how to equate to a list

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

Answers (4)

shantanoo
shantanoo

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

Adem Öztaş
Adem Öztaş

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

Anand S Kumar
Anand S Kumar

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 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 .

Upvotes: 3

The6thSense
The6thSense

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

Related Questions