Search code examples
pythongeneratorxrange

Add an arbitrary element to an xrange()?


In Python, it's more memory-efficient to use xrange() instead of range when iterating.

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

With range(), it's easy: x = range(...) + [arbitrary element].

But with xrange(), there doesn't seem to be a cleaner solution than this:

for i in xrange(...):
    if foo(i):
        ...
if foo(arbitrary element):
        ...

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


Solution

  • itertools.chain lets you make a combined iterator from multiple iterables without concatenating them (so no expensive temporaries):

    from itertools import chain
    
    # Must wrap arbitrary element in one-element tuple (or list)
    for i in chain(xrange(...), (arbitrary_element,)):
        if foo(i):
            ...