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>As far as I am aware, the only way to get the result you want is to loop through your list and detect when you encounter tuples. </p>

<p>Example which should work:</p>

<pre><code>temp = None
result = []
for item in this_list:
    if type(item) == tuple:
        if temp is not None:
            while len(temp) &lt; 3:
                temp.append(None)
            result.append(temp)
        temp = []
    temp.append(item)
</code></pre>

<p>Edit: As someone correctly commented, don't name a variable list, you'd be overwriting the built in list function. Changed name in example. </p>

python python-2.7