-1

I have a list 'x' consisted of some numbers and ideally I wish to obtain a list like 'a'

x = [12, 37, 64, 159, 205, 225, 239, 252, 257]
a = [(12,37),(37,64),(64,159),(159,205),(205,225),(225,239),(239,252),(252,257)]

I have the following code but it does not seem to do the right thing:

for i in zip(x[::2], x[1::2]):
    print(i)

I got the results like:

(12, 37)
(64, 159)
(205, 225)
(239, 252)
Tomato_Dog
  • 33
  • 4

2 Answers2

0

You can access each element by index:

x = [12, 37, 64, 159, 205, 225, 239, 252, 257] 
new_x = [[x[i], x[i+1]] for i in range(len(x)-1)]

Output:

[[12, 37], [37, 64], [64, 159], [159, 205], [205, 225], [225, 239], [239, 252], [252, 257]]

However, a zip-based solution requires simple list slicing:

new_x = list(zip(x, x[1:]))

Output:

[(12, 37), (37, 64), (64, 159), (159, 205), (205, 225), (225, 239), (239, 252), (252, 257)]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
-1
x = [12, 37, 64, 159, 205, 225, 239, 252, 257]
print([i for i in zip(x[::1], x[1::])])

Output:

[(12, 37), (37, 64), (64, 159), (159, 205), (205, 225), (225, 239), (239, 252), (252, 257)]

In slicing you need to be careful with step number as you used 2 as step number it will always used 2nd element for it's position. so instead writing x[::2] you are supposed to write x[::1] now the default step for slice is 1 hence you don't need to mention it so you can write only x instead of x[::1] and for next you can just write x[1:] instead of x[1::]

Gahan
  • 4,075
  • 4
  • 24
  • 44