-1

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?

Seikenn
  • 7
  • 5

6 Answers6

1

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.

masko
  • 19
  • 3
0

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)]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0
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.

vks
  • 67,027
  • 10
  • 91
  • 124
0

Using zip and slicing we can try s = [1,0,2,6,8]

print(list(zip(s[:-1],s[1:])))

0

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.

ndc85430
  • 1,395
  • 3
  • 11
  • 17
0

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.

Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15