3 ms·
map() isn't all that useful in Python. 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 m
by svisser 11y ago
map() isn't all that useful in Python.
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)
- fishnchips 11y agoI guess it's all about your definition of 'straightforward' ;)
- ekimekim 11y agoI 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.
- scardine 11y agoThe alternative would be: 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.
- svisser 11y agoYou can also use a generator expression so you don't have to create a list: s = sep.join(str(part) for part in parts)
- est 11y agoPython 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)