title: Is next() in python really that fast?
body: <p>Through one of the posts here, I read that using next() to search and retrieve the first occurrence of an element in the list could be fast. However, I was stunned to see the traditional for-if-break syntax perform better by quite a bit of time. Correct me if I made a mistake in my analysis. 
  Here is a snippet of what I tried:</p>
  
  <pre><code>&gt;&gt;&gt; def compare_2():
  ...     device = 'a'
  ...     l = ['a', 'b', 'c', 'd']
  ...     z = next((device for x in l if x==device), None)
  
  &gt;&gt;&gt; def compare_1():
  ...     device = 'a'
  ...     l = ['a', 'b', 'c', 'd']
  ...     z = None
  ...     for x in l:
  ...             if x == device:
  ...                     z = device
  ...                     break
  
  &gt;&gt;&gt; import timeit
  &gt;&gt;&gt; t = timeit.Timer(setup='from __main__ import compare_2', stmt='compare_2()')
  &gt;&gt;&gt; t.timeit()
  1.5207240581512451
  &gt;&gt;&gt; t = timeit.Timer(setup='from __main__ import compare_1', stmt='compare_1()')
  &gt;&gt;&gt; t.timeit()
  0.46623396873474121
  </code></pre>
  
  <p>I thought this could be happening since I was trying to search and retrieve the first element in the list as an example. I also tried with the last element and noticed that next() does not perform any better than it did before.</p>
  
  <pre><code>&gt;&gt;&gt; def compare_2():
  ...     device = 'd'
  ...     l = ['a', 'b', 'c', 'd']
  ...     z = next((device for x in l if x==device), None)
  ...
  &gt;&gt;&gt;
  &gt;&gt;&gt; def compare_1():
  ...     device = 'd'
  ...     l = ['a', 'b', 'c', 'd']
  ...     z = None
  ...     for x in l:
  ...             if x == device:
  ...                     z = device
  ...                     break
  ...
  
  &gt;&gt;&gt;
  &gt;&gt;&gt; t = timeit.Timer(setup='from __main__ import compare_2', stmt='compare_2()')
  &gt;&gt;&gt; t.timeit()
  1.6903998851776123
  &gt;&gt;&gt; t = timeit.Timer(setup='from __main__ import compare_1', stmt='compare_1()')
  &gt;&gt;&gt; t.timeit()
  0.66585493087768555
  </code></pre>
  
  <p>Would love to know when to actually use next() and when to not, in terms of optimizing the code.
  Thanks!</p>
  
  <p>UPDATE:
  <code>if device in l</code> would be definitely faster. 
  I actually just wanted to prototype a simple case. I encountered this while trying to retrieve an object from a list of objects based on an attribute match. For eg:
  obj = next(obj for obj in obj_list if obj.value == 1)</p>