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
  • ls = [1,2,3,4,5,6] [[ls[2*i],ls[2*i+1]] for i in range(len(ls)//2)] – Albert G Lieu Jan 16 '21 at 04:53
  • For those who's here to get the answer yet facing long outdated duplicate link above - I think I'd say best answer for this case would be `iterator = iter(ls)` and then `list(zip(iterator, iterator))` - gives list of tuples though. One liner for Python3.8+ would be `list(zip(iterator := iter(ls), iterator))` – jupiterbjy Jun 25 '23 at 20:22

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.

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32
1
res = [ls[i:i+2] for i in range(0,len(ls),2)]
goalie1998
  • 1,427
  • 1
  • 9
  • 16