Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list with n*n elements into n lists with n elements in every list [duplicate]

I am trying to come up with a function that takes an input x and split a big list with the number of elements x*x into x smaller lists with x elements in every list E.g:

big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

def split_list (x):
big_list = pairs (x)
small_list = [big_list[0:x] for x in range (x)]

My output has to be:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] 

but I'm not getting it, what do you recommend ?

like image 773
nazeeroo bu Avatar asked Sep 29 '17 13:09

nazeeroo bu


People also ask

How do you split a list into N parts in Python?

array_split(list, n) will simply split the list into n parts.

Can you split () a list in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a list into delimiter in Python?

Use split() method to split by delimiter. If the argument is omitted, it will be split by whitespace, such as spaces, newlines \n , and tabs \t . Consecutive whitespace is processed together. A list of the words is returned.


2 Answers

You can try this:

big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

def split_list (x):
   return [big_list[i:i+x] for i in range(0, len(big_list), x)]

print(split_list(4))

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
like image 173
Ajax1234 Avatar answered Sep 22 '22 04:09

Ajax1234


I use this code all the time.

def chunkify(items, chunk_len):
    return [items[i:i+chunk_len] for i in range(0,len(items),chunk_len)]
like image 29
Evan Avatar answered Sep 25 '22 04:09

Evan