# Split Python List by Nth Item

This has been one of the processes I’ve normally not solved in a clean or readable way.

In []: a = [1,2,3,4,5,6,7,8]


Taking the top output I want to return something similar to below.

Out[]: [(1, 2), (3, 4), (5, 6), (7, 8)]


Using a Pythonic approach this task isn’t to difficult, but there is some explaining to do.

First lets look at the code:

In []: a = iter([1,2,3,4,5,6,7,8])

In []: [ i for i in zip(a, a) ]
Out[]: [(1, 2), (3, 4), (5, 6), (7, 8)]


First we need to pass our list to the iter function, this turns our list into a iterator object:

In []: a
Out[]: <listiterator at 0x1037c3110>


This iterator can be used like any other iterator as it has a next method:

In []: a = iter([1,2,3,4,5,6,7,8])

In []: a.next()
Out[]: 1

In []: a.next()
Out[]: 2

In []: a.next()
Out[]: 3


The next bit to understand is the zip function:

In []: a = [1,2,3,4]

In []: b = [5,6,7,8]

In []: zip(a, b)
Out[]: [(1, 5), (2, 6), (3, 7), (4, 8)]


What zip does is takes the 1st object ( next method ) from each iterator-able object passed in and packs them together in a tuple, it then continues till one or all objects throws a StopIteration :

In []: a = iter([1,2])

In []: a.next()
Out[]: 1

In []: a.next()
Out[]: 2

In []: a.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-52-aa817a57a973> in <module>()
----> 1 a.next()

StopIteration:


So to put it all together zip takes our ‘a’ variable (an iter object of our list) as a argument

twice

.

[ i for i in zip(**a**, **a**) ]


Zip then grabs the first item from our first argument

using the next method,

and the first item from our second argument

using the next method

and bundles them in a tuple. If we were to do this by hand it would look like this:

In []: a = iter([1,2,3,4,5,6,7,8])

In []: first = a.next()

In []: second = a.next()

In []: first, second
Out[]: (1, 2)


Then if we were to do it again:

In []: first = a.next()

In []: second = a.next()

In []: first, second
Out[]: (3, 4)


Hopefully this makes sense now.