1

I have a list of integers like this

numbers = [1, 5, 7, 19, 22, 55]

I want to have a function that takes this as input and gives me a list of paired tuples that should contain the numbers as (1,5), (5,7), (7,19) and so on.

Kindly suggest.

I have tried using for loops. Didn't get expected output.

Rohit Rahman
  • 1,054
  • 1
  • 7
  • 13

2 Answers2

2

From Python 3.10 you can use itertools.pairwise

from itertools import pairwise

numbers = [1, 5, 7, 19, 22, 55]
list(pairwise(numbers)) # [(1, 5), (5, 7), (7, 19), (19, 22), (22, 55)]
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
0
lst = [(numbers[i],numbers[i+1]) for i in range(0,len(numbers)-1)]

This should do the trick: loop over all elements in the list numbers. You loop until the one to last element, since otherwise you would walk out of the array (get an index error).

Lexpj
  • 921
  • 2
  • 6
  • 15
  • 1
    Similarly, you could use `zip` to achieve a similar result: `[(n1, n2) for n1, n2 in zip(numbers, numbers[1:])]` – Adid Dec 04 '22 at 07:29