Failing to import itertools in Python 3.5.2

32,749

izip_longest was renamed to zip_longest in Python 3 (note, no i at the start), import that instead:

from itertools import zip_longest

and use that name in your code.

If you need to write code that works both on Python 2 and 3, catch the ImportError to try the other name, then rename:

try:
    # Python 3
    from itertools import zip_longest
except ImportError:
    # Python 2
    from itertools import izip_longest as zip_longest

# use the name zip_longest
Share:
32,749

Related videos on Youtube

Joyita Das
Author by

Joyita Das

Masters student Completing Dissertation :)

Updated on July 09, 2022

Comments

  • Joyita Das
    Joyita Das almost 2 years

    I am new to Python. I am trying to import izip_longest from itertools. But I am not able to find the import "itertools" in the preferences in Python interpreter. I am using Python 3.5.2. It gives me the below error-

    from itertools import izip_longest
    ImportError: cannot import name 'izip_longest'
    

    Please let me know what is the right course of action. I have tried Python 2.7 too and ended up with same problem. Do I need to use lower version Python.

  • Joyita Das
    Joyita Das almost 8 years
    Thanks @Martijn. Changing it to zip_longest solved my problem.