0

Is there an idiomatic way of taking two elements from an iterable like from a shift register? I have seen this, but it's another case. For the following example:

for i, j in something_i_need(range(5)):
    print("%d %d" % (i, j))

I expect the output:

0 1
1 2
2 3
3 4

I know I can perform this using:

def shift_register(it):
    it = iter(it)
    x = next(it)
    for y in it:
        yield x, y
        x = y

But i started wondering whether the python standard library contains something for this common use case so I don't have to reinvent the wheel.

In my usecase the iterator is infinite.

Community
  • 1
  • 1
Adrian Jałoszewski
  • 1,695
  • 3
  • 17
  • 33
  • This question is from 6 years ago, when python 3.2 was roaming the fields. It didn't have many of the features python has now, so the answers there might be outdated. BTW, the answer is in Python 2, which could not have some of the newest Python 3 features. – Adrian Jałoszewski May 06 '17 at 19:13
  • 1
    The question was last 'active' only 5 months ago. Moreover, it's *very* popular and used as canonical duplicate for this kind of questions. I'm certain there's nothing like that in the library (not publicly available, at least) right now, and I'm sure that someone would have added a new answer (or updated an existing one) if such feature had been added to the language. – vaultah May 06 '17 at 19:19

0 Answers0