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?

hn_tired
  • 690
  • 10
  • 21

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
  • 149
  • 4
1

An option is to use Numpy.

import numpy as np

b = np.array(a).reshape(-1, 2).tolist()
CypherX
  • 7,019
  • 3
  • 25
  • 37