I need to append the first item of a (general) iterable as the final item of that iterable (thus "closing the loop"). I've come up with the following:
from collections.abc import Iterable
from itertools import chain
def close_loop(iterable: Iterable) -> Iterable:
iterator = iter(iterable)
first = next(iterator)
return chain([first], iterator, [first])
# Examples:
list(close_loop(range(5))) # [0, 1, 2, 3, 4, 0]
''.join(close_loop('abc')) # 'abca'
Which works, but seems a bit "clumsy". I was wondering if there's a more straightforward approach using the magic of itertools
. Solutions using more_itertools
are also highly welcome.
Here is a version which doesn't use itertools
def close_loop(iterable):
iterator = iter(iterable)
first = next(iterator)
yield first
yield from iterator
yield first