0

I have a thousand numbers in a list like this:

A=[1,2,3,4]

I want to covert this in the following format:

desired_A=[[1,2],[2,3],[3,4]]

How can I do this?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

2 Answers2

2

You can use zip() and a list comprehension like:

Code:

desired = [[a, b] for a, b in zip(A, A[1:])]

Test Code:

A = [1, 2, 3, 4]
desired = [[a, b] for a, b in zip(A, A[1:])]
print(desired)

Result:

[[1, 2], [2, 3], [3, 4]]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

You can do it in one neat list comprehension. You are creating a new list where for each element in A, the new list has a list that contains that element and the element after that element.

desired_A = [[A[i], A[i+1]] for i in range(len(A)-1)]
Primusa
  • 13,136
  • 3
  • 33
  • 53