1
list = [('a5', 1), 1, ('a1', 1), 0, 0]

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.

exepected_output = [[('a5', 1), 1,None],[('a1', 1), 0, 0]]

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

data_person
  • 4,194
  • 7
  • 40
  • 75
  • 5
    how do you know if the 2nd or 3rd element is missing? – depperm Sep 23 '16 at 16:27
  • Here is how you split a [list into chunks](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Brendan Abel Sep 23 '16 at 16:29
  • As a useful aside - where do you get this data *from*? It's highly likely that there's a better way to get your data out of its native state into the state that you're looking for. – Wayne Werner Sep 23 '16 at 16:31
  • 6
    Also don't use `list` for a list name. – sisanared Sep 23 '16 at 16:33
  • Why you shouldn't use `list` as a name is because it shadows the built-in class `list`. This prevents you from accessing the class and can lead to unwanted results or errors later on in your program. – Ted Klein Bergman Sep 23 '16 at 16:52

2 Answers2

2

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.

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)]
vesche
  • 1,842
  • 1
  • 13
  • 19
1

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.

Example which should work:

temp = None
result = []
for item in this_list:
    if type(item) == tuple:
        if temp is not None:
            while len(temp) < 3:
                temp.append(None)
            result.append(temp)
        temp = []
    temp.append(item)

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

trelltron
  • 509
  • 1
  • 4
  • 8
  • 1
    last temp never gets added to result. In the rare case that the OP actually gives you a good test case, use it! Preferably before you post the answer. :) expected_output = [[('a5', 1), 1,None],[('a1', 1), 0, 0]] assert(result == expected_output) – Kenny Ostrom Sep 23 '16 at 16:53