user2821664
user2821664

Reputation: 27

Stopping a while loop when a certain element of the list is reached

places= ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center",  "LA Dodgers stadium", "Home"]
def placesCount(places):
    multi_word = 0
    count = 0
    while True:
        place = places[count]
        if ' ' in place and place!='LA Dodgers stadium' **""" or anything that comes after LA dogers stadium"""** :
            multi_word += 1
        if '' in place and place!='LA Dodgers stadium' """ **or anything that comes after LA dogers stadium**""":
            count += 1
    print (count, "places to LA dodgers stadium"),  print (multi_word)
placesCount(places)

I basically want to know how I can stop the while-loop from adding to the list when it reaches a certain element of the list ("LA Dodgers Stadium") in this case. It should not add anything after it reaches that element of the list.

Upvotes: 0

Views: 144

Answers (3)

Ludwik Trammer
Ludwik Trammer

Reputation: 25032

Your code seem to work. Here is a slightly better version:

def placesCount(places):
    count = 0
    multi_word = 0
    for place in places:
        count += 1
        if ' ' in place:
            multi_word += 1
        if place == 'LA Dodgers stadium':
            break
    return count, multi_word

Or using itertools:

from itertools import takewhile, ifilter

def placesCount(places):
    # Get list of places up to 'LA Dodgers stadium'
    places = list(takewhile(lambda x: x != 'LA Dodgers stadium', places))

    # And from those get a list of only those that include a space
    multi_places = list(ifilter(lambda x: ' ' in x, places))

    # Return their length
    return len(places), len(multi_places)

An example of how you could then use the function (that didn't change from your original example BTW, the function still behaves the same - accepts a list of places and returns a tuple with the two counts):

places = ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center",  "LA Dodgers stadium", "Home"]

# Run the function and save the results
count_all, count_with_spaces = placesCount(places)

# Print out the results
print "There are %d places" % count_all
print "There are %d places with spaces" % count_with_spaces

Upvotes: 2

Dillon Welch
Dillon Welch

Reputation: 482

This code seems to work just fine. I printed out the result of placesCount, which was (6, 5). Looks like this means the function hit 6 words, of which 5 were multi words. That fits with your data.

As Fredrik mentioned, using a for place in places loop would be a prettier way of accomplishing what you're trying to do.

Upvotes: 0

John
John

Reputation: 1

place = None
while place != 'stop condition':
    do_stuff()

Upvotes: 0

Related Questions