Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-lazy evaluation version of map in Python3?

Tags:

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?

like image 953
yegle Avatar asked Aug 25 '13 20:08

yegle


People also ask

What is the equivalent of map in Python?

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.

What is lazy evaluation in Python?

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.

What is a lazy map?

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.

What is a map function in Python 3?

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.


1 Answers

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 Nones 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) 
like image 92
Jon Clements Avatar answered Oct 02 '22 16:10

Jon Clements