I tend to use map if my mapping function is already available to me as a callable. If I would use a lambda, I tend to use a list or generator expression instead.
Probably my single most common usage of map is:
s = sep.join(map(str, parts))
because join() refuses to join anything that isn't a str, and map is a nice way to stringify all elements of a list.
Python 101: str() is dangerous for unicode objects without a specified encoding. Please don't call str() unless you know exactly what encoding you are dealing with.
Try it:
$ LC_ALL=en_US.UTF-8 python -c "print str(u'é')"
Traceback (most recent call last):
File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
To perhaps shed a little light on the None thing and why it would be useful, consider the following:
def munge(data, convert=None):
data = map(convert, data)
...
ie. treating None as identity gives you sane default behaviour in the case that you want to optionally provide a mapping functionality. Granted, you can easily do an "if convert is not None" but I think this is slightly nicer.
Welp, add it to the list of things I think are better in py2 than py3.
This is C++ style thinking, but that way it has to copy the array and run that function on every element. If it supports none it can just return the original data.
No comments yet about why in Python 3 the map behavior changed when the iterables are of different lengths? That seems like a gratuitous change. How is that better (not just different) than what Python 2 did?
Also, there was one other change in Python 3 that should have been left alone. I'm stealing the meme from a previous poster on HN:
Python 3 broke "Hello, World!"
Why? Why couldn't that "wart" have been left the way it was?
Sometimes it's smarter to not change something, especially if that change breaks nearly 100% of existing programs.
16 comments
[ 2.9 ms ] story [ 43.1 ms ] threadIf you want a list it's more straightforward to write:
If you don't want a list it's more straightforward to write:Probably my single most common usage of map is:
because join() refuses to join anything that isn't a str, and map is a nice way to stringify all elements of a list.Try it:
The documentation here actually mentions that map() and filter () are somewhat obsolete in python.
Welp, add it to the list of things I think are better in py2 than py3.
This behaviour for map with None is no longer present in python3 and raises a TypeError.
Also, there was one other change in Python 3 that should have been left alone. I'm stealing the meme from a previous poster on HN:
Why? Why couldn't that "wart" have been left the way it was? Sometimes it's smarter to not change something, especially if that change breaks nearly 100% of existing programs.Very annoying TBH. I had some really nice list chunking functions using `map` on python2 that no longer work on python3.
http://nvie.com/posts/beautiful-map/