>>> l = [1, 2, 3] >>> print(' '.join(str(x) for x in l)) 1 2 3 >>> print(' '.join(map(str, l))) 1 2 3
Here is what the above code is Doing:
1. The map function takes a function and an iterable as arguments.
2. The function is applied to all the elements of the iterable.
3. The map object is an iterator, and applying the list function to it returns a list of the results.
4. In the first call to print, the string ‘1 2 3’ is returned. In the second call, a list of strings is returned.
5. Thus, you get the same result in both cases.
For the first print call, the list comprehension is faster than the map function.
For the second print call, the map function is faster than the list comprehension.
So, it really depends on what you’re trying to do.
If you want to apply a function to all the elements of an iterable and get a list of the results, use the map function.
If you want to do something else, use a list comprehension.