How to make zip_longest available in itertools using Python 2.7

When trying to import this function in Python Jupyter 2.7 nb running on Windows 10, I get this error:

enter image description here

I believe that I have not run into problems in the past because I used Python 3. So I'm wondering if it's just not available in Python 2 or if there is a way to make it work.

+6


source to share


2 answers


For Python 3, the method zip_longest

:

from itertools import zip_longest

      



For Python 2, the method izip_longest

:

from itertools import izip_longest

      

+20


source


If you don't know which version of Python is running the script, you can use this trick:



try:
    from itertools import zip_longest
except ImportError:
    from itertools import izip_longest as zip_longest

# now this works in both python 2 and 3
print(list(zip_longest([1,2,3],[4,5])))

      

+8


source







All Articles