grouping list elements in python
<pre><code>list = [('a5', 1), 1, ('a1', 1), 0, 0]
</code></pre>

<p>I want to group the elements of the list into 3, if the second or third element is missing in the list 'None' has to appended in the corresponding location.</p>

<pre><code>exepected_output = [[('a5', 1), 1,None],[('a1', 1), 0, 0]]
</code></pre>

<p>Is there a pythonic way for this? New to this, any suggestions would be helpful.</p>

<p>Here's a slightly different approach from the other answers, doing a comparison on the type of each element and then breaking the original list into chunks.</p>

<pre><code>li = [('a5', 1), 1, ('a1', 1), 0, 0]

for i in range(0, len(li), 3):
    if type(li[i]) is not tuple:
        li.insert(i, None)
    if type(li[i+1]) is not int:
        li.insert(i+1, None)
    if type(li[i+2]) is not int:
        li.insert(i+2, None)

print [li[i:i + 3] for i in range(0, len(li), 3)]
</code></pre>

python python-2.7