Search code examples
python-3.xdeque

Why Python 3 map function is not called when deque is used?


The argument function of map does not be called when I use deque as input for it.

If I just loop it and call rotate function, it worked.

Why res does not rotate at all after map function?

>>> print(res)
[deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3])]
>>> map(lambda x: x.rotate(1), res)
<map object at 0x10a35b7f0>
>>> print(res)
[deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3]), deque([4, 5, 1, 2, 3])]

However if I used for loop it is rotated.

>>> for x in res:
...     x.rotate(1)
...
>>> print(res)
[deque([3, 4, 5, 1, 2]), deque([3, 4, 5, 1, 2]), deque([3, 4, 5, 1, 2]), deque([3, 4, 5, 1, 2]), deque([3, 4, 5, 1, 2])]
>>>

Solution

  • map (like a generator expression) is lazy. It doesn't iterate the list and evaluate its function until you force it to, and you aren't forcing the iterator to run here.

    You could force it by putting it in a list (or using a comprehension from the start):

    list(map(lambda x: x.rotate(1), res))
    

    list forcibly evaluates the returned map.

    Ideally though, you shouldn't be using map to carry out side effects. The purpose of map is to transform one list into another. Just use your full for loop here for clarity.