0

I have a list like this

x = [1,2,3,4,5,6] 

and i want this:

x = [(1,2),(2,3),(3,4),(4,5),(5,6)]

I am interested in knowing if there is a library that performs this procedure directly. otherwise, how to do it with some function

rhuilipan
  • 11
  • 1
  • 2
    What did you try? – Rahul Dec 24 '21 at 13:30
  • Yes - there are many ways to achieve this easily with builtin functions - the 2 common ways to achieve this use either `zip` and `iter`; or `range` and list `slices`. Come back once you have tried some approaches – match Dec 24 '21 at 13:34
  • Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – match Dec 24 '21 at 13:38

2 Answers2

1

Out of many ways, you can use python listcomp here.

[(x[i], x[i+1]) for i in range(len(x) - 1)]

P.S.: Stackoverflow is not for these type of questions. Please try atleast some way before asking question.

Rahul
  • 10,830
  • 4
  • 53
  • 88
0

You can use this function:

def f(x):
    res: list[tuple] = []
    for i in range(len(x)-1):
        res.append((x[i], x[i+1]))
    return res

test:

In [5]: def f(x):
   ...:     res: list[tuple] = []
   ...:     for i in range(len(x)-1):
   ...:         res.append((x[i], x[i+1]))
   ...:     return res
   ...: 

In [6]:  x = [1,2,3,4,5,6]

In [7]: f(x)
Out[7]: [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
cup11
  • 177
  • 7