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']
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']
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']
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']