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 ?
array_split(list, n) will simply split the list into n parts.
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.
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.
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]]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With