Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A simple, flexible one line version:</p> <pre><code>[i for (i, item) in enumerate([('a', 1), ('b', 3), ('a', 5)]) if item[0] == 'a'] # returns [0, 2] [i for (i, item) in enumerate([('a', 1), ('b', 3), ('a', 5)]) if item[0] == 'a'][0] # returns 0 </code></pre> <p>You could wrap it in a function, replace <code>item[0] == 'a'</code> with a call to an arbitrary predicate (like in my original answer; that's where it's flexible) etc. The second version above will throw an exception if no item is found, so wrap it in try/except; the first one will return an empty list.</p> <hr> <p>If you prefer a separate function for the job, check out the one below... It has the benefit of <strong>only consuming as much of your iterable as needed</strong> to find an appropriate item.</p> <p>Original answer:</p> <p>This will allow you to find the index of the first item possessing any property you can think of, though you'll need to express it as a function (a <code>lambda x: x[0] == 'a'</code> suffices in your example case):</p> <pre><code>def index_by(pred, iterable): i = 0 found = False for item in iterable: if pred(item): found = True break i += 1 return i if found else None </code></pre> <p>Call like so:</p> <pre><code>index_by(lambda x: x[0] == 'a', [('b', 1), ('a', 5)]) # returns 1 </code></pre> <p>to obtain the zero-based index of the first item in the iterable which satisfies the given predicate. (In other words, the first item in the iterable passed in as the second argument for which the function passed in as the first argument returns a true value.)</p> <p>If the iterable does not contain an element satisfying the predicate, <code>None</code> is returned.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload