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):
		ugh.append(1)
	else:
		ugh.append(0)

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

You are commenting using your Twitter 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.

%d bloggers like this: