Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list_split
#1
"""
Create a function called list_split, taking the arguments I (iterable) and
N (numeric). The goal of the function would be to split the iterable I into
multiple sublists of length N.
The function must:
  1. Split the iterable I into multiple sublists, all of which are N-elements
  long (except for the last sublist, which can be shorter, if there are less
  than N elements remainig). Return a new list composed of all sublists, in order.
  2. When inspected, would return the following help string:
    Split an iterable I into sublist of at most N elements

Hint: The built-in range() function takes an optional third argument that is
used to specify the step between the iterations

For example:
  list_split([1,2,3,4,5,6,7], 2) -> [[1,2],[3,4],[5,6],[7]]
  list_split('abcdefghijk', 3) -> ['abc','def','ghi','jk']
"""

def list_split(*args):
    I = args[0]
    N = args[1]
    n = max(1, N)
    return (I[i:i+n] for i in range(0, len(I), n))


x = [1,2,3,4,5,6,7]
y = 2

list_split(x,y)
 what am i doing wrong here why is it not spitting out the result
Reply
#2
You're returning a generator via comprehension syntax here. I recommend you use a regular for loop to construct your list instead.
Reply
#3
And you forgot to print the output:

print(list_split(x,y))
Reply
#4
Or, you can wrap what you return in a call to list(), which will exhaust the generator and give a list.  Or you can replace the parenthases with square brackets to use a list comprehension instead of a generator comprehension.  So the last line of your function would be either...
# wrap in list...
return list(I[i:i+n] for i in range(0, len(I), n))

# or, change to a list comprehension...
return [I[i:i+n] for i in range(0, len(I), n)]
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020