0

Say I’ve got a list

ls = [1,2,3,4,5,6]

And I’d like to get this result:

res = [[1,2],[3,4],[5,6]]

What’s the cleanest way to go about this?

Knkemora
  • 5
  • 2

2 Answers2

2

I'm a big fan of the zip call, which allows you to group lists. So, something like:

ls = [1,2,3,4,5,6]
res = list(zip(ls[::2], ls[1::2]))

should do the trick.

ls[::2] extracts all the even-numbered list items (I say this because index 0 is "even"). And ls[1::2] grabs all the odd-numbered list items. Then the zip call pairs them off like you want.

Be aware that zip can take more than two lists, as well. Have a look at the online docs to get more info. Also, in Py2, the zip call returned a list (I believe), but in Py3 it returns a zip object, which you can cast as a list to get the desired output.

Gary02127
  • 4,543
  • 1
  • 22
  • 27
1
res = [ls[i:i+2] for i in range(0,len(ls),2)]
goalie1998
  • 1,319
  • 1
  • 8
  • 15