0
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.

3
  • what is the line **place = places[count]**? Commented Oct 14, 2013 at 11:27
  • @MrE it is the bolded line which is not displayed bold because it is formatted as source code. ...and by the way it is initializing the variable place before used in the while loop. Commented Oct 14, 2013 at 11:28
  • 2
    Why not just places.index('Sochi') which will return the index for the string 'Sochi' in the list and since lists are zero-indexed you'll get the sought after number Commented Oct 14, 2013 at 11:30

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

This feels more Python, whilst a while loops feels more C/C++
1
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.

Comments

1

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.

1 Comment

I'd keep the count < len(places) condition. If "Sochi" is not in the list, you'll get out of bounds after the end.
1

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])

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.