I have a list [1,0,2,6,8]
and I want to split it as this[(1,0),(0,2),(2,6),(6,8)]
where each element of the result is a tuple, how can I write my code?
6 Answers
If you use python 3.10, you can use pairwise
from itertools
:
from itertools import pairwise
pairwise([1, 0, 2, 6, 8])
If you want the result as a list instead of iterator, surround pairwise
with list
.

- 19
- 3
Using zip
we can try:
inp = [1, 0, 2, 6, 8]
print(list(zip(inp[0:4], inp[1:5]))) # [(1, 0), (0, 2), (2, 6), (6, 8)]

- 502,043
- 27
- 286
- 360
x=[1,0,2,6,8]
zip(x, x[1:])
Should do it.If python 3 you can make a list out of it before tring as it returns iterator.

- 67,027
- 10
- 91
- 124
Using zip and slicing we can try s = [1,0,2,6,8]
print(list(zip(s[:-1],s[1:])))

- 1
- 1
-
No need to slice the first list. `list(zip(s, s[1:]))` is enough. – blhsing May 25 '22 at 06:55
The third-party Toolz library has a function sliding_window
to do this, as well as lots of other useful functions:
>>> from toolz.itertoolz import sliding_window
>>> list(sliding_window(2, [1,0,2,6,8]))
[(1, 0), (0, 2), (2, 6), (6, 8)]
Note that the functions in Toolz generally return lazy sequences (in the same way that range
and zip
do, for example), so I've called list
explicitly to consume that.

- 1,395
- 3
- 11
- 17
An alternative without using zip, which may result more friendly if you're starting to code:
x = [1,0,2,6,8]
[(x[i], x[i+1]) for i in range(len(x)-1)]
But zip is the way to go in general if you want, well... to zip items.

- 1,594
- 2
- 6
- 15