-3

I have this code:

table is a list.

if 'ping' in table or 'pong' in table:
    # Do something here

Is there a shorter way to write this? I don't want to have table duplicated in the if statement.

Scope
  • 1
  • Why do you want a shorter way of doing this? This way is fine. It is readable and efficient. Do you expect the number of items you need to check to grow indefinitely? – juanpa.arrivillaga Nov 29 '18 at 22:19

2 Answers2

0

You can use set.intersection:

if {'ping', 'pong'}.intersection(table):
    # Do something here
blhsing
  • 91,368
  • 6
  • 71
  • 106
-2

You can use map:

>>> table = 'pong'
>>> if any(map(lambda pattern: pattern in table, ['ping', 'pong'])):
...     print('found!')
...
found!

or:

>>> table = 'pong'
>>> if any(pattern in table for pattern in ['ping', 'pong'])):
...     print('found!')
...
found!
sokoli
  • 501
  • 3
  • 10