0

Im trying to write a function that creates set of dynamic sublists each containing 5 elements from a list passed to it.Here's my attempt at the code

def sublists(seq):
    i=0
    x=[]
    while i<len(seq)-1:
        j=0
        while j<5:
            X.append(seq[i]) # How do I change X after it reaches size 5?
     #return set of sublists

EDIT:

Sample input: [1,2,3,4,5,6,7,8,9,10]

Expected output: [[1,2,3,4,5],[6,7,8,9,10]]

2
  • 1
    It's not clear what output do you expect. Give us example please. Commented May 16, 2012 at 5:07
  • Then it is the duplicate of stackoverflow.com/questions/312443/… Commented May 16, 2012 at 5:29

3 Answers 3

3

Well, for starters, you'll need to (or at least should) have two lists, a temporary one and a permanent one that you return (Also you will need to increase j and i or, more practically, use a for loop, but I assume you just forgot to post that).

EDIT removed first code as the style given doesn't match easily with the expected results, see other two possibilities.

Or, more sensibly:

def sublists(seq):
    x=[]
    for i in range(0,len(seq),5):
        x.append(seq[i:i+5])
    return x

Or, more sensibly again, a simple list comprehension:

def sublists(seq):
    return [seq[i:i+5] for i in range(0,len(seq),5)]

When given the list:

l = [1,2,3,4,5,6,7,8,9,10]

They will return

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
Sign up to request clarification or add additional context in comments.

1 Comment

:Great answer! I really wanted your second explanation , Thanks!
0

Have you considered using itertools.combinations(...)?

For example:

>>> from itertools import combinations
>>> l = [1,2,3,4,5,6]
>>> list(combinations(l, 5))
[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]

2 Comments

doesnt help to solve my issue, please look at the edited question!
@KodeSeeker my apologies, I misunderstood the intent of your question.
0

By "dynamic sublists", do you mean break up the list into groups of five elements? This is similar to your approach:

def sublists(lst, n):
    ret = []
    i = 0
    while i < len(lst):
        ret.append(seq[i:i+n])
        i += n
    return ret

Or, using iterators:

def sublists(seq, n):
    it = iter(seq)
    while True:
        r = list(itertools.islice(it, 5))
        if not r:
            break
        yield r

which will return an iterator of lists over list of length up to five. (If you took out the list call, weird things would happen if you didn't access the iterators in the same order.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.