0

I can not figure out why my code does not filter out lists from a predefined list. I am trying to remove specific list using the following code.

data = [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
data = [x for x in data if x[0] != 1 and x[1] != 1]

print data

My result:

data = [[2, 2, 1], [2, 2, 2]]

Expected result:

data = [[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
4
  • 1
    In [1, 2, 1], x[0] == 1 so it automatically disqualifies it. And so on and so forth... Commented Oct 26, 2012 at 22:42
  • 1
    To match the way you're thinking of the problem, use: if not (x[0] == 1 and x[1] == 1) Commented Oct 26, 2012 at 22:44
  • You're welcome. Note that it's logically equivalent to using or, as the other guys suggested: because not (A and B) == (not A) or (not B) Commented Oct 26, 2012 at 22:50
  • Turned the above into an answer, if you feel like accepting it... Commented Oct 26, 2012 at 22:58

5 Answers 5

3

and is wrong, use or

data = [x for x in data if x[0] != 1 or x[1] != 1]
Sign up to request clarification or add additional context in comments.

Comments

2

and is only true if both sides are true values. Perhaps you want...

data = [x for x in data if x[0] != 1 or x[1] != 1]

Comments

0

I think this is what the OP wants.

data = [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]

data = [x for x in data if x[:2] != [1,1]]
print data

data = [x for x in data if ((x[0],x[1]) != (1,1))]   
print data

2 Comments

Good one as well! But this is not so well adaptable if I would want to filter by 1st and 3rd value of list instead.
How about the second solution.
0

You had a small logic error. To match the way you're thinking of the problem, use:

if not (x[0] == 1 and x[1] == 1)

Note that this is logically equivalent to using or, as the other guys suggested:

not (A and B) == (not A) or (not B) 

Comments

0

In your code "or" should be used in the place of "and". And "and" is used if u want to execute both the values. Example:

data = [x for x in data if x[0] != 1 or x[1] != 1]

Comments

Your Answer

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.