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?
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?
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.