Add an arbitrary element to an xrange()?
<p>In Python, it's more memory-efficient to use <code>xrange()</code> instead of <code>range</code> when iterating.</p>

<p>The trouble I'm having is that I want to iterate over a large list -- such that I need to use <code>xrange()</code> and after that I want to check an arbitrary element.</p>

<p>With <code>range()</code>, it's easy: <code>x = range(...) + [arbitrary element]</code>.</p>

<p>But with <code>xrange()</code>, there doesn't seem to be a cleaner solution than this:</p>

<pre><code>for i in xrange(...):
    if foo(i):
        ...
if foo(arbitrary element):
        ...
</code></pre>

<p>Any suggestions for cleaner solutions? Is there a way to "append" an arbitrary element to a generator?</p>

<p>I would recommend keeping the <code>arbitrary_element</code> check out of the loop, but if you want to make it part of the loop, you can use <a href="https://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain</code></a>:</p>

<pre><code>for i in itertools.chain(xrange(...), [arbitrary_element]):
    ...
</code></pre>

python generator xrange