Non-lazy evaluation version of map in Python3?
Using map
for its side-effects (eg function call) when you're not interested in returned values is undesirable even in Python2.x. If the function returns None
, but repeats a million times - you'd be building a list of a million None
s just to discard it. The correct way is to either use a for-loop and call:
for row in data:
writer.writerow(row)
or as the csv
module allows, use:
writer.writerows(data)
If for some reason you really, really wanted to use map
, then you can use the consume
recipe from itertools and generate a zero length deque, eg:
from collections import deque
deque(map(writer.writerow, data), maxlen=0)
You can set up a zero length deque to do this:
with open("output.csv", "w") as f:
writer = csv.writer(f)
collections.deque(map(writer.writerow, data),0)
This is the same way that itertools.consume(iterator, None)
recipe works. It functionally will exhaust the iterator without building the list.
You can also just use the consume recipe from itertools
.
But a loop is more readable and Pythonic to me, but YMMV.
If you don't care about the return value, then map
is not the best tool for the job. A simple for
would be better:
for d in data:
writer.writerow(d)
That'll work fine in Python 2.x and 3.x. Notice that map
is useful when you want to create a new list, if you're traversing over an iterable just for the effect, then use a for
.