Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use iter function to loop through a list until a certain match is found [closed]

I frankly don't understand how to use the iter(o[,sentinel]) function and I'm trying to loop through lst(a list) and print all the values until 'kdawg'

Code:

lst = [2,3,4,'kdawg',5,6,'hey']

class foo:
    def __str__(self):
        return str(lst)

for i in iter(foo,'kdawg'):
    print i

I expect it to return:

2
3
4

However it returns the whole list continuously:

[2,3,4,'kdawg',5,6,'hey']

Why doesn't my iter() function work?

like image 929
K DawG Avatar asked Oct 27 '25 14:10

K DawG


1 Answers

Use itertools.takewhile():

>>> from itertools import takewhile
>>> 
>>> l = [2,3,4,'kdawg',5,6,'hey']
>>> 
>>> for i in takewhile(lambda s: s != 'kdawg', l):
...     print i
... 
2
3
4
like image 164
arshajii Avatar answered Oct 29 '25 14:10

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!