That's like your solution with the utility lists but a bit shorter:
L = [1,2,3,4,5,6]
for i in zip(L, L[1:]):
print(list(i))
# [1, 2]
# [2, 3]
# [3, 4]
# [4, 5]
# [5, 6]
This works as expected because zip
stops as soon as one iterable is exhausted.
You could additionally use map
to convert the items immediatly:
for i in map(list, zip(L, L[1:])):
print(i)
or if you want the whole thing converted to a list of lists:
list(map(list, zip(L, L[1:])))
# [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
If your lists are really long creating a new list (because I sliced it with [1:]
) might be expensive, then you could avoid this by using itertools.islice
:
for i in zip(L, islice(L, 1, None)):
print(list(i))