-1

From nosklo's answer in What is the most “pythonic” way to iterate over a list in chunks? what is the return line doing:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

I understand what the output will be, I'd just like to know how this works.

EDIT: Adding use case to hopefully clear up confusion.

I am using the defined function to read in a list of unknown size and grab 8 objects from it, run those 8 through something, and then grab the next 8 and so forth until the list is completed. Use case from nosklo's post:

animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']

for group in chunker(animals, 3):
    print group
# ['cat', 'dog', 'rabbit']
# ['duck', 'bird', 'cow']
# ['gnu', 'fish']
JohnD
  • 61
  • 6

1 Answers1

2

(<expr> for <var> in <itr>) is a generator expression. Equivalent to

def anon():
    for <var> in <itr>:
        yield <expr>
anon()

seq[<start>:<stop>] is slice notation. For lists, it will make a new list object with the elements in that range. Should have the same effect as [seq[i] for i in range(<start>, <stop>)].

range(<start>, <stop>, <step>) is the range builtin. Generates an iterable of integers.

len(seq) length builtin. Same as seq.__len__(), which is supposed to get the "length" of the object. It's up to the object to decide what this means, but for sequence types like list it should be the number of elements.

gilch
  • 10,813
  • 1
  • 23
  • 28
  • Many thanks gilch. "seq[:] is slice notation." is exactly the information I needed and thanks for taking the time to explain it all. – JohnD Jan 02 '19 at 15:40