0

I want to loop through a list and terminate when I reach a certain value. Something like:

ls = ['yes','yes','stop','yes']

while a in ls <> 'stop':
    print a

Would print:

yes
yes

I know I can do:

for a in ls:
    if a == 'stop':
        break
    print a

but it seems messy.

2
  • 1
    It might be "messy", but it is perfectly clear & does the job Commented Dec 18, 2014 at 2:50
  • 1
    Also, you should not be using <>. That operator was deprecated in Python 2.5 and removed entirely from Python 3.x. You should be using != instead. Commented Dec 18, 2014 at 3:01

2 Answers 2

4

You could use list indexing and slicing:

print ls[:ls.index('stop')]
# => ['yes', 'yes']

In a loop:

for a in ls[:ls.index('stop')]:
    print a
Sign up to request clarification or add additional context in comments.

Comments

4

You could use itertools.takewhile:

>>> from itertools import takewhile
>>> ls = ['yes','yes','stop','yes']
>>> for i in takewhile(lambda x: x != 'stop', ls):
...     i
...
'yes'
'yes'
>>>

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.