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?
map
for side effects is what's odd. Python 2map
also collects the return values. The new behavior merely highlights it further. Just don't do that, use a for loop. – Huskampmap
for side effect. – Huppertlist(map(lambda x:2*x, [1,2,3]))
– Emeliaemelinmap
shall be a lazily-evaluated function more in line with other languages. In any case, I find myself typing[*map(...)]
almost all the time when I'm using Python for scientific statistics, where usually an immediate result is needed (e.g.numpy.array(...)
understands lists but not generators). So the non-lazy map is the superior default for some applications. – Musicianshiplmap
andamap
that add the necessary boiler plate to immediately collect the results ofmap()
as a list or np.array, respectively. It makes the code significantly cleaner, easier to read, and easier to maintain. Scattering casts tolist
or[*map(...)]
everywhere, or using a list comprehension whenmap
is much more succinct, just looks sloppy. – Musicianship