Split list after 2 values in python

Question:

Given a list like this:

list = ['tree', 'grass', 'banana', 'apple', 'fork', 'spoon', 'dog', 'cat']

What would be the best way to go about splitting the list into 2 new lists every 2 values?

Results:

list_1 = ['tree', 'grass', 'fork', 'spoon']
list_2 = ['banana', 'apple', 'dog', 'cat']
Asked By: Link

||

Answers:

We can try using a list comprehension with index here:

inp = ['tree', 'grass', 'banana', 'apple', 'fork', 'spoon', 'dog', 'cat']
list_1 = [x for ind, x in enumerate(inp) if ind % 4 <= 1]
list_2 = [x for ind, x in enumerate(inp) if ind % 4 > 1]

print(list_1)  # ['tree', 'grass', 'fork', 'spoon']
print(list_2)  # ['banana', 'apple', 'dog', 'cat']
Answered By: Tim Biegeleisen
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.