I'm trying to use map
in Python3. Here's some code I'm using:
import csv data = [ [1], [2], [3] ] with open("output.csv", "w") as f: writer = csv.writer(f) map(writer.writerow, data)
However, since map
in Python3 returns an iterator, this code doesn't work in Python3 (but works fine in Python2 since that version of map
always return a list
)
My current solution is to add a list
function call over the iterator to force the evaluation. But it seems odd (I don't care about the return value, why should I convert the iterator into a list?)
Any better solutions?
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
If you've never heard of Lazy Evaluation before, Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (From Wikipedia). It's usually being considered as a strategy to optimize your code.
map is lazy simply means it doesn't immediately build a complete list of results but waits for you to require the next result before doing the call to f and produce it.
Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With