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.

5
  • 5
    how do you know if the 2nd or 3rd element is missing? Commented Sep 23, 2016 at 16:27
  • Here is how you split a list into chunks Commented Sep 23, 2016 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. Commented Sep 23, 2016 at 16:31
  • 6
    Also don't use list for a list name. Commented Sep 23, 2016 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. Commented Sep 23, 2016 at 16:52

2 Answers 2

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)]
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.