Pergunta

I am confused on the proper way to do this in python.... So if I want to iterate through a list using a for loop and check if each element of list 'A' is in either of 2 or more other lists but I don't seem to understand how to do this... here is some basic code of what I mean:

>>> a
[1, 2, 3, 4, 5]
>>> even
[2, 4]
>>> odd
[1, 3]
>>> for i in a:
...     if i in even or odd:
...             print(i)
... 
1
2
3
4
5

Why is this code printing 5 since 5 is not in the even list nor the odd list?? Also what is the proper way to do this so that I can iterate through one list and check if each element is in ATLEAST one of some other amount of lists?

Foi útil?

Solução

The problem is here: i in even or odd

This is parsed as such:

(i in even) or (odd).

Python unhelpfully tries to convert the odd list into a boolean value (in this case True because the list is not empty).

Try i in even or i in odd, which correctly checks if i is present in either even or odd.

Outras dicas

You need to use in twice:

if i in even or i in odd:

i in even will check if i is in even. i in odd will check if i is in odd.


Otherwise, your code will be evaluated like this:

if (i in even) or (odd):

Moreover, the condition of the if-statement will always evaluate to True because odd is a non-empty list (which always evaluate to True in Python).


Finally, you need to remember that, even though its syntax is somewhat similar, Python is not English. :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top