neversaint
neversaint

Reputation: 64054

Breaking the loop after string check in python

I have the following list:

str_list = [1,3,"foo bar",10]

What I want to do is to simply iterate through it print the results. Stop if the iteration meets "foo bar".

I tried the following code:

In [6]: for x in str_list:
   ...:     print x
   ...:     if x is "foo bar":
   ...:         break
   ...:     

It continues to print string with and after "foo bar". It didn't to to what I expect it to do, i.e. simply printing this:

1
3

What's the right way to do it?

Upvotes: 0

Views: 201

Answers (5)

MrAlias
MrAlias

Reputation: 1346

You need to print the items of the list after you check for the desired string.

for x in str_list:
    if x == "foo bar":
        break
    print(x)

However there are more pythonic ways of doing this:

 try:
     foo_idx = str_list.index('foo bar')
 except ValueError:
     print(str_list)
 else:
     print(str_list[:foo_idx])

And if you wanted this to return something formated like you were showing in your questions:

 try:
     foo_idx = str_list.index('foo bar')
 except ValueError:
     print('\n'.join(map(str, str_list)))
 else:
     print('\n'.join(map(str, str_list[:foo_idx])))

Upvotes: 1

Abhishek Mittal
Abhishek Mittal

Reputation: 366

str_list = [1,3,"foo bar",10]

for x in str_list:
     if x is "foo bar":
         break
     print x

Upvotes: 0

Abhijit
Abhijit

Reputation: 63757

itertools.takewhile was written specifically for this purpose, though I am not a particular fan as it add an unnecessary function call through lambda and often its difficult to debug

>>> from itertools import takewhile
>>> for elem in takewhile(lambda e: e != "foo bar", str_list):
    print elem


1
3

Upvotes: 2

shaktimaan
shaktimaan

Reputation: 12092

You just need to print after checking. And if it is the string you are looking for in the check, just break. Like this:

>>> str_list = [1,3,"foo bar",10]
>>> for item in str_list:
...     if item == 'foo bar':
...         break
...     print item
...
1
3

Also, it is important to note the difference between using is and using ==. As mentioned in this answer, is checks if both the variables point to the same object. == checks if objects referred to by the variables are equal. So you should be using == here.

Upvotes: 2

ssm
ssm

Reputation: 5383

The easiest way of doing this is by splitting using your desired value ...

Let us say that you have the list

s = [1,3,"foo bar",10]

Then,

s[:s.index('foo bar')]

is a list till the location of 'foo bar'. Of course, if 'foo bar' isn't in the list, then it will throw an error. Then you can change the above line to

s[:s.index('foo bar')] if 'foo bar' in s else s

Upvotes: 0

Related Questions