2

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

I Have a function like below:

def split_list(self,my_list,num):    
    .....    
    .....

where my_list is:

my_list = [['1','one'],['2','two'],['3','three'],['4','four'],['5','five'],['6','six'],['7','seven'],['8','eight']]

I want to split list by given num:

i.e if num = 3 then output will be : [[['1','one'],['2','two'],['3','three']],[['4','four'],['5','five'],['6','six']],[['7','seven'],['8','eight']]]

if num =4 then

[[['1','one'],['2','two'],['3','three'],['4','four']],[['5','five'],['6','six'],['7','seven'],['8','eight']]]
Community
  • 1
  • 1
Avadhesh
  • 4,519
  • 5
  • 33
  • 44

3 Answers3

3

I'd just use a list comprehension/generator:

[my_list[x:x+num] for x in range(0, len(my_list), num)]
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
0
def split_list(lst, num):
    def splitter(lst, num):
        while lst:
            head = lst[:num]
            lst = lst[num:]
            yield head
    return list(splitter(lst, num))

Here is an excerpt from running this in the interactive shell:

>>> def split_list(lst, num):
...     def splitter(lst, num):
...         while lst:
...             head = lst[:num]
...             lst = lst[num:]
...             yield head
...     return list(splitter(lst, num))
...
>>> split_list(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
0

Try to read this: How do you split a list into evenly sized chunks?

Community
  • 1
  • 1
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52