Home > Software design >  separate a list in parentheses keeping them inside a list
separate a list in parentheses keeping them inside a list

Time:12-25

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

CodePudding user response:

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.

CodePudding user response:

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)]
  • Related