matthewr
matthewr

Reputation: 324

Evaluate once if string not in item when iterating over list - python 3.x

I want to use this in an if statement so it would be useful if the output is a bollean expression but is there an easy way to find if string is not found in an item within a list?

e.g.

string_foo='teen'

list_foo=['one','two','three']

the problem is i need a loop to output somthing if a string is not found within an item in a list, the problem i have with doing it this way:

[print('no') if string_foo not in i for i in list_foo]

Is that for every item where string_foo isnt in i, it will print 'no' whereas i want it to only print 'no' once if string_foo isnt found within an item in list_foo

Upvotes: 1

Views: 52

Answers (3)

jpp
jpp

Reputation: 164773

Don't use the side effects of list comprehensions

List comprehensions are to build new lists, not for their side effects. print returns None, so you are creating and discarding a list of None values. This is wasteful.

any / all + generator comprehension

One solution is to use any with a generator comprehension:

if not any(string_foo in i for i in list_foo):
    print('no')

Or equivalently with all:

if all(string_foo not in i for i in list_foo):
    print('no')

Write a function

Generators / generator expressions have overheads which you may find expensive. A regular function may be more efficient:

def any_in_list(mystr, lst):
    for i in lst:
        if mystr in i:
            return True
    return False

if not any_in_list(string_foo, list_foo):
    print('no')

for / else loop + break

If you don't want to write a generic function, you can replicate via a for / else construct with break:

for i in list_foo:
    if string_foo in i:
        break
else:
    print('no')

Upvotes: 4

Pumpkin
Pumpkin

Reputation: 233

This does what you want:

if any(x in i for i in things):
    print("in it")
else:
    print("not in it")

The any function returns true if any of the list items is true.

Upvotes: 0

Jacob Howell
Jacob Howell

Reputation: 11

The following should work. list_foo is only a list of strings so you don't need to loop over each item, you can just check to see if string_foo exists in the list or not.

if string_foo not in item:
  print('no')

Upvotes: 0

Related Questions