Newb - 7 months ago 35

Python Question

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

`xrange()`

`range`

The trouble I'm having is that I want to iterate over a large list -- such that I need to use

`xrange()`

With

`range()`

`x = range(...) + [arbitrary element]`

But with

`xrange()`

`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

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