Python, if any() else in list comprehension

This one took me about 20-30 minutes to figure out today and required stringing together some SO answers, so I’m putting what I learned here for future reference.
The scenario: searching if 1 of multiple strings exists in a longer string.  In this case, some possible Twitter clients in the source field of a tweet object.

The answer:

these = ['Twitter Web Client', 'Hootsuite']
desktop = [1 if any(x in item for x in these) else 0 for item in data['source']]

The loop version of the code is

these = ['Twitter Web Client', 'Hootsuite']
ugh = []
for item in data['source']:
	if any(x in item for x in these):

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.