0

have below list

a = [1,2,3,4,5,6,7,8,9,10]

and want to convert to below:

b = [[1,2],[3,4],[5,6],[7,8],[9,10]]

tried below but result not true

b = [i for i in a[::2]]

how can do it and what is shortest way?

motad333
  • 482
  • 4
  • 16

2 Answers2

1

another possible way slightly different to @Mesejo's way suggested in the comment would be:

n=2
[a[idx:idx+n] for idx in range(0, len(a), n)]
cotrane
  • 111
  • 3
1

An option is to use Numpy.

import numpy as np

b = np.array(a).reshape(-1, 2).tolist()
CypherX
  • 6,127
  • 3
  • 16
  • 30