I can't find imap() in itertools in Python 3

Question:

I have a problem that I want to solve with itertools.imap(). I imported itertools and called itertools.imap(), but apparently itertools doesn’t have attribute imap. What’s going wrong?

>>> import itertools
>>> dir(itertools)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper',     '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
>>> itertools.imap()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
itertools.imap()
AttributeError: 'module' object has no attribute 'imap'
Asked By: user3905370

||

Answers:

You are using Python 3, therefore there is no imap function in itertools module. It was removed, because global function map now returns iterators.

Answered By: Konstantin

itertools.imap() is in Python 2, but not in Python 3.

Actually, that function was moved to just the map function in Python 3 and if you want to use the old Python 2 map, you must use list(map()).

Answered By: markzz

If you want something that works in both Python 3 and Python 2, you can do something like:

try:
    from itertools import imap
except ImportError:
    # Python 3...
    imap=map
Answered By: dawg

How about this?

imap = lambda *args, **kwargs: list(map(*args, **kwargs))

In fact!! 🙂

import itertools
itertools.imap = lambda *args, **kwargs: list(map(*args, **kwargs))
Answered By: Inversus

I like the python-future idoms for universal Python 2/3 code, like this:

# Works in both Python 2 and 3:
from builtins import map

You then have to refactor your code to use map everywhere you were using imap before:

myiter = map(func, myoldlist)

# `myiter` now has the correct type and is interchangeable with `imap`
assert isinstance(myiter, iter)

You do need to install future for this to work on both 2 and 3:

pip install future
Answered By: hobs

You can use the 2to3 script (https://docs.python.org/2/library/2to3.html) which is part of every Python installation to translate your program or whole projects from Python 2 to Python 3.

python <path_to_python_installation>Toolsscripts2to3.py -w <your_file>.py

(-w option writes modifications to file, a backup is stored)

Answered By: user2757572
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.