seeker
seeker

Reputation: 7011

Creating dynamic sublists from a list /sequence in python

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]]

Upvotes: 0

Views: 778

Answers (3)

Josiah
Josiah

Reputation: 3326

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]]

Upvotes: 3

Danica
Danica

Reputation: 28856

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.)

Upvotes: 0

srgerg
srgerg

Reputation: 19339

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)]

Upvotes: 0

Related Questions