list item's position
Steven Bethard
steven.bethard at gmail.com
Thu Jan 20 00:02:51 EST 2005
Bill Mill wrote:
> 2 solutions:
>
> In [98]: bars = ["str", "foobaz", "barbaz", "foobar"]
>
> In [99]: for bar in bars:
> ....: if 'bar' in bar and 'baz' in bar:
> ....: print bar
> ....: print bars.index(bar)
> ....:
> barbaz
> 2
>
> In [100]: for i in range(len(bars)):
> .....: if 'bar' in bars[i] and 'baz' in bars[i]:
> .....: print bars[i]
> .....: print i
> .....:
> barbaz
> 2
>
> The first one is slow and pretty, the second one is fast and (a bit)
> ugly. I believe that you should avoid range(len(x)) when you can, but
> use it when you need to know the index of something without an
> additional x.index() call.
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):
py> bars = ["str", "foobaz", "barbaz", "foobar"]
py> for i, bar in enumerate(bars):
... if 'bar' in bar and 'baz' in bar:
... print bar
... print i
...
barbaz
2
The only time where I even consider using range(len(x)) is when I don't
also need to look at the item -- which I find to be quite uncommon...
Steve
More information about the Python-list
mailing list