I just extracted some data from a list using python but think it’s overcomplicated and unpythonic and there’s probably a much better way to do this. I’m actually pretty sure I saw this somewhere in the standard library docs but my brain refuses to tell me where.
So here it goes:
Input:
x = range(8) # any even sequence
Output:
[[0, 1], [2, 3], [4, 5], [6, 7]]
My take:
[ [x[i], x[i+1]] for i in range(len(x))[::2] ]
Tuples?
In Python 2.n
In Python 3.n
zip()behaves slightly differently…Lists?
The implementation is the same in Python 2 and 3…
Or, alternatively:
The latter is more useful if you want to split into
lists of 3 or more elements, without spelling it out, such as:If
zip(*2*[iter(x)])looks a little odd to you (and it did to me the first time I saw it!), take a look at How doeszip(*[iter(s)]*n)work in Python?.See also this pairwise implementation, which I think is pretty neat.