Caesius
Caesius

Reputation: 267

Python 3: find previous/next element in for loop

This question has been answered before for Python 2.x. I can not get it to work in Python 3.

I changed izip to zip, because I understood izip was removed from Python 3.

from itertools import tee, islice, chain

def previous_and_next(some_iterable):
    prevs, items, nexts = tee(some_iterable, 3)
    prevs = chain([None], prevs)
    nexts = chain(islice(nexts, 1, None), [None])
    print(zip(prevs, items, nexts))

a = list(range(1,10))

previous_and_next(a)

Running this gives me <zip object at 0x7f338e4ea638>

What is wrong with this code?

Upvotes: 0

Views: 103

Answers (1)

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

<zip object at 0x7f338e4ea638> is an iterator. To obtain the items in the iterator one must pass it to tuple() or list(). Specifically, replace print(zip(prevs, items, nexts)) with print(tuple(zip(prevs, items, nexts))) or print(list(zip(prevs, items, nexts)))

Upvotes: 1

Related Questions