1

I have a list like the following:

original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 

And my desired output is:

result = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]

Here, the items of 'result' will be each one list of two items from the original_list. so if the total no of items in original_list is 8 then it will give like the following:

original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 

And my desired output is:

result = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

I tried to solve that using 2 dimensional matrix but its not working as the elements of the original_list is sometimes even and odd.

any suggestion how can i follow?

Funny Boss
  • 328
  • 1
  • 3
  • 12
  • 3
    Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – ggorlen Feb 24 '20 at 06:10

2 Answers2

3

Is this what you want?

original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
result = []

for i in range(0, len(original_list), 2):
    result.append(original_list[i:i+2])
Pavan Skipo
  • 1,757
  • 12
  • 29
0
def split_array(original_list,split_size):

    result = []

    for i in range(0, len(original_list), split_size):
        result.append(original_list[i:i+split_size])

    return result
original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print(split_array(original_list,2))
Ananth.P
  • 445
  • 2
  • 8