user2821664
user2821664

Reputation: 27

Using while loops to count elements in a list

places = ["Jack", "John", "Sochi"]
count=0
multi_word=0
place  = places[count]
while place != "Sochi" and count < len(places):
    if ' ' in place:
        multi_word += 1

    count += 1
    place = places[count]

print ('Number of cities before Sochi:', count)

My code should print the number of cities before Sochi excluding Sochi . I don't understand what this line (place = places[count]) does, nor do I understand why I need it twice.

Upvotes: 0

Views: 7817

Answers (4)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Why not try a more pythonic solution instead ?

places = ["Jack", "John", "Sochi"]

try:
    count = places.index("Sochi")
except ValueError:
    count = len(places)

multi_word = len([place for place in places[:count] if ' ' in place])

Upvotes: 1

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

foreach would neaten it up

places = ["Jack", "John", "Sochi"]
count = 0
for place in places:
    if ' ' in place:
        multi_word += 1
    if place == "Sochi":
        break
    count += 1

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122376

You can use the following while loop to check for the number of places before Sochi:

places = ["Jack", "John", "Sochi"]
count = 0
multi_word = 0
while count < len(places):
    place = places[count]
    if ' ' in place:
        multi_word += 1
    if place == "Sochi":
        break
    count += 1

print('Number of cities before Sochi:', count)

The break statement means you'll exit your while loop.

Upvotes: 1

dornhege
dornhege

Reputation: 1500

count=0
place = places[count]

Now place is always places[0], i.e. Jack. Thus the while loop only terminates on the second condition, giving you the list length of 3.

place = places[count] should go in the loop.

Upvotes: 1

Related Questions