1

I want to carry this out :

if ('a' or 'b' or 'c' or 'd') in ['1' , '@' , 'L' , 'b' , '+']:
    print("Valid")

Since 'b' is present in the list the output should be "Valid" but instead there is no output. After searching for so long I found that multiple 'or's cannot be used. Is there any other way? P.S. if this is put instead :

if ('a' or 'b') in ['1' , '@' , 'L' , 'b' , '+']:
    print("Valid")

The output is "Valid" but I want multiple elements in tuple

Justin Fay
  • 2,576
  • 1
  • 20
  • 27
qwer ty
  • 23
  • 2

2 Answers2

2

Python any()

The any() method returns True if any element of an iterable is True. If not, any() returns False.

if you want to check at least one matches:

if any(x in ['1', '@', 'L', 'b', '+'] for x in ('a','b','c','d')):
    print("Valid")

NOTE:

Your logic of using boolean operators on string is wrong.

The output of the boolean operations between the strings depends on following things:

  1. Python considers empty strings as having boolean value of ‘false’ and non-empty string as having boolean value of ‘true’.
  2. For ‘and’ operator if left value is true, then right value is checked and returned. If left value is false, then it is returned
  3. For ‘or’ operator if left value is true, then it is returned, otherwise if left value is false, then right value is returned.

what means that result of ('a' or 'b' or 'c' or 'd') will be 'a'

and then you have : if 'a' in ['1', '@', 'L', 'b', '+']:

Community
  • 1
  • 1
ncica
  • 7,015
  • 1
  • 15
  • 37
0

You could use sets for this

>>> if set(['1', '@', 'L', 'b', '+']).intersection(set(['a', 'b', 'c', 'd'])):
...     print('valid')
... 
valid
Justin Fay
  • 2,576
  • 1
  • 20
  • 27