a1204773
a1204773

Reputation: 7043

Check for strings inside list python

Lets say I have

a = "FIFA 13"

then I writing

"bla" and "13" in a

And result is true... Why? bla is not in the a

Upvotes: 1

Views: 416

Answers (4)

Andrew Clark
Andrew Clark

Reputation: 208475

Your boolean expression is being evaluated as ("bla") and ("13" in a), non-empty strings evaluate as true, so if "13" in a is true then the entire expression will evaluate as true.

Instead, use all():

all(x in a for x in ("bla", "13"))

Or just check both separately:

"bla" in a and "13" in a

Upvotes: 8

Blender
Blender

Reputation: 298176

Your code isn't interpreted like it is read:

("bla") and ("13" in a)

"bla" is truthy, so it automatically evaluates to True. "13" in a might be True. False and True evaluates to True, so "bla" isn't really taken into consideration.

You have to be a bit more explicit:

'bla' in a and '13' in a

Or you can use an unreadable one-liner:

all(map(a.__contains__, ('bla', '13')))

For a short-circuiting one-liner, I think you'll have to use itertools.imap instead of map..

Upvotes: 2

Maxime Chéramy
Maxime Chéramy

Reputation: 18831

"bla" is true

"13" in a is true

Hence, "bla" and "13" in a is true

What you wanted to write is probably : ("bla" in a) and ("13" in a)

Upvotes: 2

Roland Smith
Roland Smith

Reputation: 43495

You should use

In [1]: a = "FIFA 13"

In [2]: "bla" in a and "13" in a
Out[2]: False

Upvotes: 3

Related Questions