Skip to content

Instantly share code, notes, and snippets.

@smarnach
Created December 10, 2014 12:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smarnach/75146be0088e7b5c503f to your computer and use it in GitHub Desktop.
Save smarnach/75146be0088e7b5c503f to your computer and use it in GitHub Desktop.
import itertools
def variable_grouper(it):
"""Group the input iterable into chunks of sizes read from the iterable itself.
Example:
Input iterable: 2 a b 3 c d e
Output iterable: (a b) (c d e)
"""
it = iter(it)
while True:
group_length = next(it)
yield itertools.islice(it, group_length)
# Code written to work in both Python 2 and 3
print(list(map(tuple, variable_grouper([2, "a", "b", 3, "c", "d", "e"]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment