list item's position

John Machin sjmachin at lexicon.net
Thu Jan 20 01:22:17 EST 2005


On Wed, 19 Jan 2005 22:02:51 -0700, Steven Bethard
<steven.bethard at gmail.com> wrote:

>
>See Mark's post, if you "need to know the index of something" this is 
>the perfect case for enumerate (assuming you have at least Python 2.3):

But the OP (despite what he says) _doesn't_ need to know the index of
the first thingy containing both a bar and a baz, if all he wants to
do is remove earlier thingies.

def barbaz(iterable, bar, baz):
    seq = iter(iterable)
    for anobj in seq:
        if bar in anobj and baz in anobj:
            yield anobj
            break
    for anobj in seq:
        yield anobj

>>> import barbaz
>>> bars = ["str", "foobaz", "barbaz", "foobar"]
>>> print list(barbaz.barbaz(bars, 'bar', 'baz'))
['barbaz', 'foobar']
>>> print list(barbaz.barbaz(bars, 'o', 'b'))
['foobaz', 'barbaz', 'foobar']
>>> print list(barbaz.barbaz(bars, '', 'b'))
['foobaz', 'barbaz', 'foobar']
>>> print list(barbaz.barbaz(bars, '', ''))
['str', 'foobaz', 'barbaz', 'foobar']
>>> print list(barbaz.barbaz(bars, 'q', 'x'))
[]
>>>






More information about the Python-list mailing list