I want (for learning purposes, but please let me know if there is a built-in function that does this), to define a function that takes:
- Input: a list
[x_1, ... x_k]
- Input: a number
n
and returns a list of lists:
- output:
[ [x_1...x_n], [x_n 1,...m x_n n], ...... [...x_k] ]
which basically "splits" the input-list into lists of size n
, (the last list is allowed to have smaller size).
Example 1: f([1,2,3,4,5,6,7],2) = [[1,2], [3,4] , [5,6], [7] ]
Example 2: f([1,2],2) = [ [1,2] ]
Example 3: f([1],2) = [ [1] ]
Example 4: f([]) = [ [] ]
I tried to implement the function as follows:
def split_in_pieces(l,n): # Split a list into a list of lists, each of size n (the last one can be smaller).
if len(l) <= n:
return [l]
else:
tail = l[n:]
recursive_result = split_in_pieces(tail, n) # Recursively split the rest of the list.
# Now return the list with the first element,
# concatenated with the recursive result
return recursive_result.insert(0,l[:n])
This code however does not work. If I try:
r = split_in_pieces(range(30),2)
I get the following error:
AttributeError: 'NoneType' object has no attribute 'insert'
Can somebody please help understanding what is going on?
thanks!
CodePudding user response:
The insert()
method modifies the list in-place and returns None
. You need to return recursive_result
:
def split_in_pieces(l,n): # Split a list into a list of lists, each of size n (the last one can be smaller).
if len(l) <= n:
return [l]
else:
tail = l[n:]
recursive_result = split_in_pieces(tail, n) # Recursively split the rest of the list.
# Now return the list with the first element,
# concatenated with the recursive result
recursive_result.insert(0,l[:n])
return recursive_result
CodePudding user response:
There is no built-in function (that I know of) that will do this. However, it's very easy to implement with a list comprehension - i.e., no need for recursion.
For example:
def split_in_pieces(lst, n):
return [lst[offset:offset n] for offset in range(0, len(lst), n)]
print(split_in_pieces(list(range(10)), 2))
Output:
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]