List of integers to pairs of tuples
Question:
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.
Answers:
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).
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)]
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.
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).
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)]