Mad Map: Python Road
kalnitsky.org
kalnitsky.org
The documentation here actually mentions that map() and filter () are somewhat obsolete in python.
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.
def munge(data, convert=lambda x: x)If you want a list it's more straightforward to write:
[f(x) for x in my_iterable]
If you don't want a list it's more straightforward to write: for x in my_iterable:
y = f(x)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. s = sep.join([str(part) for part in parts])
I agree this is one of the cases where map looks nicer than list comprehensions or generator expressions. s = sep.join(str(part) for part in parts)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)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.Very annoying TBH. I had some really nice list chunking functions using `map` on python2 that no longer work on python3.
map(lambda x: x, ['a', 'b', 'c'], [1, 2])
This should be map(lambda x, y: (x, y), ['a', 'b', 'c'], [1, 2])
If you want the same behavior as passing None as the first argument.This behaviour for map with None is no longer present in python3 and raises a TypeError.
filter(None, [0 1, 2, 3, False, None, 5, 6, 7])
Here None is the same as bool()