What is not working with my "map" usage?

Viet Nguyen vhnguyenn at yahoo.com
Fri Sep 21 17:29:41 EDT 2018


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)
<class 'str'>
i = 2
BEFORE total = 0
AFTER total = 2

<class 'str'>
i = 09
BEFORE total = 2
AFTER total = 11

<class 'str'>
i = 49
BEFORE total = 11
AFTER total = 60

FINAL total = 60

========
## Why is this NOT Okay when I use map ??  What must I change ?

>>> list(map(add_all_elements,alist))
<class 'str'>
i = 2
BEFORE total = 0
AFTER total = 2

FINAL total = 2

<class 'str'>
i = 09
BEFORE total = 0
AFTER total = 9

FINAL total = 9

<class 'str'>
i = 49
BEFORE total = 0
AFTER total = 49

FINAL total = 49

[2, 9, 49]


Thanks,
Viet



More information about the Python-list mailing list