Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When the list is so small there is no significant difference between the two. If the input list can grow large then there is a worse problem: you're iterating over the whole list, while you could stop at the first element. You could accomplish this with a for loop, but if you want to use a comprehension-like statement, here come <em>generator expressions</em>:</p> <pre><code># like list comprehensions but with () instead of [] gen = (b for a, b in foo if a == 'b') my_element = next(gen) </code></pre> <p>or simply:</p> <pre><code>my_element = next(b for a, b in foo if a == 'b') </code></pre> <p>If you want to learn more about generator expressions give a look at <a href="http://www.python.org/dev/peps/pep-0289/" rel="nofollow noreferrer">PEP 289</a>.</p> <hr> <p>Note that even with generators and iterators you have more than one choice.</p> <pre><code># Python 3: my_element = next(filter(lambda x: x[0] == 'b', foo)) # Python 2: from itertools import ifilter my_element = next(ifilter(lambda (x, y): x == 'b', foo)) </code></pre> <p>I personally don't like and don't recommend this because it is much less readable. It turns out that this is actually slower than my first snippet, but more in general using <code>filter()</code> instead of a generator expression might be faster in some special cases.</p> <p>In any case if you need benchmarking your code, I recommend using <a href="http://docs.python.org/2/library/timeit.html" rel="nofollow noreferrer">the <code>timeit</code> module</a>.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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