0

I'm trying to write a while loop that goes through a certain list looking for certain substrings. It will find words with those substrings and print out those strings.

Here is a example that works perfectly but for only one word:

lista = ['applepie','appleseed','bananacake','bananabread']

i = 0
z = len(lista)
while i < z:
    if ('pie' in lista[0+i]) == True:
        print(lista[0+i])
        break
    i = i  + 1
else:
    print('Not There Yet')

This prints out applepie (which is what is desired!).

How do I go about fixing this while loop to add in multiple constraints?

I'm trying to do this:

lista = ['applepie','appleseed','bananacake','bananabread']

i = 0
z = len(lista)
while i < z:
    if ('pie' in lista[0+i]) == True:
        print(lista[0+i])
    if ('cake' in lista[0+1]) == True:
        print(lista[0+i])
    i = i  + 1
else:
    print('Not There Yet')

This prints out: applepie Not There Yet

When I want this to print out: applepie bananacake

I used multiple 'if' statements, because I know if I want to use an 'elif', it will only run if the first 'if' statement is false.

Any help is appreciated!

2
  • 1
    'cake' in lista[0+1] should be 'cake' in lista[i] (not sure why you're adding 0... but it should be i, not 1) Commented Jun 3, 2020 at 3:10
  • Why are you doing lists like this rather than a regular for loop?!? Commented Jun 3, 2020 at 3:25

2 Answers 2

1

You have two issues smallish issues and I think one larger. The first of the two small ones are what Nick and Brenden noted above. The second is your conditional. It should be <= as opposed to the < you used.

The larger seems that you're having a problem conceptualizing the actual workings. For that, let me suggest you step through it here

Sign up to request clarification or add additional context in comments.

Comments

0

You can use any() to go through a list of conditions. It will evaluate to True when the condition is first met and False if it never happens. If you combine that with a regular python for loop, it will be nice a succinct:

lista = ['applepie','appleseed','bananacake','bananabread']
words = ['pie', 'cake']

for food in lista:
    if any(word in food for word in words):
        print(food)

It prints:

applepie
bananacake

You can also so the same thing as a list comprehension to get a list of words that match:

lista = ['applepie','appleseed','bananacake','bananabread']
words = ['pie', 'cake']

found = [food for food in lista if any(word in food for word in words)]
# ['applepie', 'bananacake']

Generally speaking, Python discourages you from using indices in loops unless you really need to. It tends to be error prone and harder to read.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.