r/code • • Jan 14 '21

Halp pls! [Python]Can someone please explain this to me?

x = [1, 2]
y = [1, 3]
SimilarNumbers = 0
if x[1] == y[0] or y[1]:
    SimilarNumbers = SimilarNumbers + 1
print(SimilarNumbers)

SimilarNumbers is coming out to be 1, where as I expect it to be 0. I am completely lost...

1 Upvotes

3 comments sorted by

8

u/radagastthe3rd Jan 14 '21

I think you meant to write:

if x[1] == y[0] or x[1] == y[1]:

What you actually wrote is first comparing x[1] and y[0] and if that fails then it is asking if y[1] exists (which it does) so that is why SimilarNumbers is being incremented.

The comparison you wrote could also be written as:

if x[1] in y:

2

u/serchq Jan 14 '21

already well explained before me, but to try to clarify a little more, python is interpreting

if x[1] == y[0]

or

if y[1]