Take the 2-minute tour ×

I found the following code that is compatible with python2

from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

However, this isn't working with Python 3. I get the following error

ImportError: cannot import name izip_longest

Can someone help?

I'd like to convert my list of [1,2,3,4,5,6,7,8,9] to [[1,2,3],[4,5,6],[7,8,9]]


Now Python3 compatible

Code below is adapted from the selected answer. Simply change name from izip_longest to zip_longest.

from itertools import zip_longest
def grouper(n, iterable, padvalue=None):
  return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
share|improve this question
Read the docs! The Python 3 version of the itertools module documentation has the updated recipe for grouper: docs.python.org/py3k/library/itertools.html#itertools-recipes –  Ned Deily May 2 '11 at 1:36
add comment

1 Answer

up vote 15 down vote accepted

In Python 3's itertools there is a function called zip_longest. It should do the same as izip_longest from Python 2.

Why the change in name? You might also notice that itertools.izip is now gone in Python 3 - that's because in Python 3, the zip built-in function now returns an iterator, whereas in Python 2 it returns a list. Since there's no need for the izip function, it also makes sense to rename the _longest variant for consistency.

share|improve this answer
Thanks @Ben James. I added a code example in the question so it's be easier for people to get a more "compiled" answer :) –  naomik May 1 '11 at 19:09
add comment

Your Answer


