Antoni Parellada
Antoni Parellada

Reputation: 4801

How to make zip_longest available in itertools using Python 2.7

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

enter image description here

I believe I hadn't encountered problems in the past because I was using Python 3. So I wonder if it is just that it is not available in Python 2, or if there is a way of making it work.

Upvotes: 13

Views: 15876

Answers (2)

Alireza Afzal Aghaei
Alireza Afzal Aghaei

Reputation: 1235

If you don't know which version of python runs 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])))

Upvotes: 9

Ajax1234
Ajax1234

Reputation: 71461

For Python 3, the method is zip_longest:

from itertools import zip_longest

For Python 2, the method is izip_longest:

from itertools import izip_longest

Upvotes: 34

Related Questions