On Saturday, September 22, 2018 at 6:22:32 AM UTC-7, Peter Otten wrote: > Victor via Python-list wrote: > > > Let me use a different input args and display them below. Basically, I am > > hoping to add up all elements of each nested list. So at first it should > > start with [1,11,111] ==> 1+11+111 = 123. But instead, it appears to take > > the 1st element from each nested list to add up [1,2,3] = 6. How should > > it be corrected? Thx. > > I see three options. You can > > (1) use a list comprehension > > [add_all_elements(*sub) for sub in alist] > > (2) replace map() with itertools.starmap() > > list(itertools.starmap(add_all_elements, alist)) > > (3) change your function's signature from add_all_elements(*args) to > add_all_elements(args), either by modifying it directly or by wrapping it > into another function > > list(map(lambda args: add_all_elements(*args), alist)) > > (3a) My personal preference would be to change the signature and then use > the list comprehension > > def add_all_elements(args): ... > [add_all_elements(sub) for sub in alist]
Hi Peter, Thank you for your suggested solutions. They all work. But I just want to know what is wrong with my doing: list(map(add_all_elements,*alist)) Theoretically, each list element is passed to add_all_elements. And if my alist is [[1, 11, 111], [2, 22, 222], [3, 33, 333]], then the 1st list element must be this [1,11,111] passed as args into add_all_elements. In other words, the following should have happened: >>> add_all_elements (*[1,11,111]) My args = (1, 11, 111) i = 1 BEFORE total = 0 AFTER total = 1 i = 11 BEFORE total = 1 AFTER total = 12 i = 111 BEFORE total = 12 AFTER total = 123 FINAL total = 123 123 Again, thanks! -- https://mail.python.org/mailman/listinfo/python-list