seven11
seven11

Reputation: 43

Python - Problem with checking if element is in list

I came across a problem in Python and since I do this for fun and not as a professional I don't get why this does not work. I have a list that contains other lists with two numbers in each one. This function should check wether the element +1 and the element -1 are elements of my tp list. If yes, append them to stack. Code:

def check():
    tp = [[0, 1], [1, 1], [1, 2], [2, 2], [2, 3], [3, 3]]
    stack = []
    for i in tp:
        a = i[0]
        b = i[1]
        if [(a - 1), (b - 1)] and [(a + 1), (b + 1)] in tp:
            stack.append(i)
    return stack

Unfortunately the output is:

[[0, 1], [1, 1], [1, 2], [2, 2]]

[1, 2] is correct because [0, 1] and [2, 3] are elements of tp.

[2, 2] is correct because [1, 1] and [3, 3] are elements of tp.

Why does this function give me the other two also? For instance: first element of tp is [0,1] -> [-1,0] and [1,2] should be the calculated outputs but obviously [-1,0] is not in this list. Where is my (probably obvious) mistake? Thanks in advance.

Upvotes: 2

Views: 156

Answers (4)

Niels Henkens
Niels Henkens

Reputation: 2696

Right now you are checking two things:

1: [(a - 1), (b - 1)] is not empty (which is always True in your example)

2: [(a + 1), (b + 1)] in tp

What you want to check is: ([(a - 1), (b - 1)] in tp) and ([(a + 1), (b + 1)] in tp)

def check():
    tp = [[0, 1], [1, 1], [1, 2], [2, 2], [2, 3], [3, 3]]
    stack = []
    for i in tp:
        a = i[0]
        b = i[1]
        if [(a - 1), (b - 1)] in tp and [(a + 1), (b + 1)] in tp:
            stack.append(i)
    return stack

Upvotes: 0

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9572

The conditional statement you have is not correct.

It should be:

if [(a - 1), (b - 1)] in tp and [(a + 1), (b + 1)] in tp:

instead of:

if [(a - 1), (b - 1)] and [(a + 1), (b + 1)] in tp:

With if [(a - 1), (b - 1)] and [(a + 1), (b + 1)] in tp, the condition is evaluated to True if:

  1. [(a - 1), (b - 1)] satisfies meaning the list is not empty
  2. [(a + 1), (b + 1)] in tp satisfies

Since condition 1 is always True, it boils down to the second condition which is also satisfied for [0, 1] and [1, 1] so you get that in the result as well.

Upvotes: 0

Barmar
Barmar

Reputation: 781058

and doesn't distribute over in. Your condition is being parsed as

if [(a - 1), (b - 1)] and ([(a + 1), (b + 1)] in tp):

Since [(a - 1), (b - 1)] is truthy, the condition always succeeds.

You need to use in for each list you want to check:

if [(a - 1), (b - 1)] in tp and [(a + 1), (b + 1)] in tp:

Upvotes: 0

Ron Serruya
Ron Serruya

Reputation: 4426

if [(a - 1), (b - 1)] and [(a + 1), (b + 1)] in tp
Should be if [(a - 1), (b - 1)] in tp and [(a + 1), (b + 1)] in tp

[(a - 1), (b - 1)] by itself is a non-empty list, which is considered truthy, making your if if True and [(a + 1), (b + 1)] in tp

Upvotes: 1

Related Questions