Newb Newb - 1 year ago 53
Python Question

Add an arbitrary element to an xrange()?

In Python, it's more memory-efficient to use

instead of
when iterating.

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

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

But with
, 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?

Answer Source

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):