create a list, named a, containing 'apple', 'banana', 'strawberry', 'apple'
a = ['apple','banana','strawberry','apple']
check if 'apple' is in the list
#option 1
'apple' in a
True
#option 2
for item in a:
if item == 'apple':
print('yes')
yes yes
Use a for loop to run the following steps on the list variable a:
if "apple" is found: print out a sentence "apple is found" and then terminate the whole for loop using break.
for item in a:
if item == 'apple':
print('apple is found')
break
#ask yourself how many of iterations does this for loop run?
apple is found
use a for loop on the list variable a to count how many times 'apple' appeared?
Tip: you need to create one variable outside the for-loop to save the count. For instance,
count = 0
for item in a:
if item xxxx:
count +=1
print(count)
count = 0
for item in a:
if item == 'apple':
count += 1
print(count)
2