Index and Slice a Generator in Python

import itertools class Indexable(object): def __init__(self,it): self.it = iter(it) def __iter__(self): return self.it def __getitem__(self,index): try: return next(itertools.islice(self.it,index,index+1)) except TypeError: return list(itertools.islice(self.it,index.start,index.stop,index.step)) You could use it like this: it = Indexable(fib()) print(it[10]) #144 print(it[2:12:2]) #[610, 1597, 4181, 10946, 28657] Notice that it[2:12:2] does not return [3, 8, 21, 55, 144] since the iterator had already … Read more

Why is the range object “not an iterator”? [duplicate]

The range object is iterable. However, it’s not an iterator. To get an iterator, you need to call iter() first: >>> r=range(5,15) >>> next(iter(r)) 5 >>> next(iter(r)) 5 >>> next(iter(r)) 5 >>> next(iter(r)) 5 >>> i=iter(r) >>> next(i) 5 >>> next(i) 6 >>> next(i) 7 >>> next(i) 8 >>> iter(r) <range_iterator object at 0x10b0f0630> >>> … Read more

Is there a library function in Python to turn a generator-function into a function returning a list?

To the best of my knowledge (and I’ve looked, because I’ve wondered exactly the same thing), no: there is no direct way of doing this with the standard library. There is a thoroughly tested listify wrapper in unstdlib.py library, though: https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149 def listify(fn=None, wrapper=list): “”” A decorator which wraps a function’s return value in “list(…)“. … Read more

Python 3: send method of generators

When you use send and expression yield in a generator, you’re treating it as a coroutine; a separate thread of execution that can run sequentially interleaved but not in parallel with its caller. When the caller executes R = m.send(a), it puts the object a into the generator’s input slot, transfers control to the generator, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)