Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating list of paired elements in python

I want to create a list of paired numbers. For example, I have a list of numbers as follows:

a = [1, 4, 7, 10, 13, 16, 19, 21, 24, 27, 30]

I want to create a paired list like this:

paired_list_a = [[1,3],[4,6],[7,9],[10,12],[13,15],[16,18],[19,20],[21,23],[24,26],[27,29]]

That is, I want to skip the first element and pair the numbers with the one next to them with minus one.

I tried something like this but no luck

paired_list_a = [1, 4, 7, 10, 13, 16, 19, 21, 24, 27, 30]
row = [[a[i],a[i+1]-1] for i in range(len(a))]

but it is throwing IndexError: list index out of range

Can anyone help me with this?

like image 920
user86907 Avatar asked Apr 29 '26 14:04

user86907


2 Answers

Use zip here with all values of same list without first value:

row = [[x, y - 1] for x, y in zip(a, a[1:])]
print (row)

[[1, 3], [4, 6], [7, 9], [10, 12], [13, 15], [16, 18], [19, 20], [21, 23], [24, 26], [27, 29]]
like image 53
jezrael Avatar answered May 02 '26 03:05

jezrael


That's because the last number doesn't has a successor. You should try something like:

row = [[a[i],a[i+1]-1] for i in range(len(a)-1)]

If you have a pattern in the numbers (for example: every item is last_item + 2) you could pair the last value without the cycle.

row[-1] = [a[-1], a[-1]+2]
like image 29
Paulo Padilla Avatar answered May 02 '26 04:05

Paulo Padilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!