0

I want to check an entire list for a specific string, if the string was not found in the list then it would print out "No string found".

This seems like a very simple question but I am drawing a blank on how to do this.

Code:

for item in lists:
    if apple in item:
        print(item)

    #if looped through entire lists and none are found
        #print("No string found!")

Sorry if this is very basic, I just cant seem to think of how to do this in python.

jaz
  • 19
  • 1
  • 6
  • Here's a whole lot discussion regarding what you are looking for [Fastest way to check if a value exists in a list](https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exists-in-a-list) – exan Feb 27 '20 at 03:34

4 Answers4

1

You could have a flag that tracks if an item is found. After the loop is finished, the flag will be True if an item has been found at least once, allowing you to print accordingly:

found = False
for item in lists:
    if apple in item:
        print(item)
        found = True
if not found:
    print("No string found!")

This means you are only iterating over the list once, which is more efficient than checking it multiple times

Parakiwi
  • 591
  • 3
  • 19
1

You can use the not keyword in addition to the in keyword. For example:

if string not in list:
    print("No string found!")

No loop needed.

OctopusProteins
  • 23
  • 1
  • 11
0

You can use for - else here for identifying the found and not found scenarios:

for item in lists:
    if apple == item:
        print('string found')
        break
else:
    print('string not found')

Or better, just a membership check on list can avoid iteration (if this is not nested):

if apple in lists:
    print('string found')
else:
    print('string not found')
Austin
  • 25,759
  • 4
  • 25
  • 48
0

you have to put apple in between quotations, it defines apple as a string.

lists = ['appletree', 'orange', 'gosh', 'apple']
string = 0
for i in lists:
  if 'apple' in i:
    string = 1
if string == 0:
  print('No string found')
else:
  print('string found')
yonny
  • 1
  • 1