Could you say me, how to write a function, which takes as its (one an only) argument a list of numbers and returns a list of string representations of those numbers?
For example toNum([1, 2, 3, 4]) returns ["1", "2", "3", "4"].
def to_num(a): return map(str, a) print to_num([1, 2, 3, 4]) prints
['1', '2', '3', '4'] map() though: (1) It's faster and (2) it's less verbose. I personally find it also more readable in simple cases like this one. And map() is still there even in Python 3, so it seems kind of pointless to claim that just any use of this built-in function is not "Pythonic" (a pretty meaningless word anyway).map() and filter() stayed, so you can hardly call it unPythonic. However, using a lambda expression with map() instead of using a list comprehension crosses the line into code that wouldn't make it through any code review I was involved in.using list comprehension:
def stringify(input): return [str(num) for num in input] map())Adrien already gave you an elegant answer:
def stringify(input): return [str(num) for num in input] That works perfectly, but if you intend to only iterate through the representations (and don't need to keep the whole list in memory for any other reason), you should instead do:
(str(num) for num in the_list) The parenthesis instead of the brackets indicate a generator expression, just as iterable as a list, but won't fully expand on creation. This may be important if your list is large.
>>> squares = [x * x for x in range(5)]; type(squares) produces <class 'list'>range(), dict.keys(), dict.values() and dict.items().