list item's position

Bill Mill bill.mill at gmail.com
Wed Jan 19 22:33:56 EST 2005


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.

Peace
Bill Mill
bill.mill at gmail.com


On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith
<bob_smith_17280 at hotmail.com> wrote:
> Hi,
> 
> I have a Python list. I can't figure out how to find an element's
> numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing:
> 
> for bar in bars:
>     if 'str_1' in bar and 'str_2' in bar:
>        print bar
> 
> This finds the right bar, but not its list position. The reason I need
> to find its value is so I can remove every element in the list before it
> so that the bar I found somewhere in the list becomes element 0... does
> that make sense?
> 
> Thanks,
> 
> Bob
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list