##Why the results of these two ways are different?##
my_list = [a, b, c]
def printable(x):return x*3
printable(my_list)
with this
list(map(printable,my_list)
??
CodePudding user response:
When the * operator is used on a list, the result is just that list repeated n times. For example,
[1, 2, 3] * 3 would yield [1, 2, 3, 1, 2, 3, 1, 2, 3]
.
However if you want to multiply each element of the list by a number n, you'd use the second method. The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
That is why you are getting different results.
CodePudding user response:
Checking the Python docs for map
, we can see that it takes map(function, iterable)
in which it applies the function
to every item in iterable
.
In this particular case, it seems like you only want to provide one argument, which just happens to be an iterable itself. So we can wrap your argument with a list as such to get the desired result:
>> list(map(printable,[my_list]))[0]
>> ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
>> my_list = ['a', 'b', 'c']
>> def printable(x):return x*3
>> printable(my_list)
>> ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']