What is not working with my "map" usage?

Thomas Jollans tjol at tjol.eu
Fri Sep 21 18:05:24 EDT 2018


On 21/09/2018 23:29, Viet Nguyen via Python-list wrote:
> Hi,
> 
> I want to add up all of the list elements.  But when I use the "map" function, it didn't seem to work as I expect.  Could someone point out how "map" can be applied here then?
> 
> def add_all_elements (*args):
>      total = 0
>      for i in args:
>         print(type(i))
>         print("i = %s" % i)
>         print("BEFORE total = %s" % total)
>         total += int(i)
>         print("AFTER total = %s\n" % total)
>      print("FINAL total = %s\n" % total)
>      return total
> 
> 
> alist = ['2', '09', '49']
> 
> 
> ## this one works Okay
> 
> add_all_elements(*alist)

 > [...]

>>>> list(map(add_all_elements,alist))

Read the output in both cases and try to figure out what 'args' is. Or 
you could print out 'args' at the top of your function to lend you a 
hand. That should help you understand what the difference between the 
two cases is, and what map() is doing.

Good luck!
Thomas



More information about the Python-list mailing list