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><a href="https://docs.python.org/3/library/itertools.html#itertools.chain"><code>itertools.chain</code></a> lets you make a combined iterator from multiple iterables without concatenating them (so no expensive temporaries):</p>

<pre><code>from itertools import chain

# Must wrap arbitrary element in one-element tuple (or list)
for i in chain(xrange(...), (arbitrary_element,)):
    if foo(i):
        ...
</code></pre>

python generator xrange