How to look ahead one element (peek) in a Python generator?

For sake of completeness, the more-itertools package (which should probably be part of any Python programmer’s toolbox) includes a peekable wrapper that implements this behavior. As the code example in the documentation shows: >>> p = peekable([‘a’, ‘b’]) >>> p.peek() ‘a’ >>> next(p) ‘a’ However, it’s often possible to rewrite code that would use this … Read more

tech