Find Items & Indices In A List...

Joachim Bauch jojo at struktur.de
Fri Dec 10 10:10:53 EST 2004


Hi Andrea,

andrea.gavana at agip.it wrote:
>       I was wondering if there is a faster/nicer method (than a for loop)
> that will allow me to find the elements (AND their indices) in a list that
> verify a certain condition. For example, assuming that I have a list like:
> 
> mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]
> 
> I would like to find the indices of the elements in the list that are equal
> to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
> use a for loop but I was wondering if there is a faster method...

you could use something like this:

 >>> mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]
 >>> [x[0] for x in enumerate(mylist) if x[1] == 1]
[1, 2, 3, 4, 9]

Greetings,
   Joachim

-- 
Joachim Bauch, struktur AG
Download icoya OpenContent 1.3 for FREE!    visit http://www.icoya.de/iOC4free <-
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 262 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20041210/c5139679/attachment.sig>


More information about the Python-list mailing list