Python Forum
Exercise about list of lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Exercise about list of lists (/thread-9907.html)



Exercise about list of lists - Otbredbaron - May-03-2018

Hi,

I'd like to know if this is the correct way to approach this kind of problem.
Basically I need to store the sum of every list of L in a new list.
For example: [[1, 2, 3], [5, 6]] => [6, 11]

#!/usr/bin/python3

L = [[1,2,3],[5,6],[6,7]] 
a = []

for i in range(0, len(L)):
    sum = 0
    for k in L[i]:
        sum += k
    a.append(sum)
print (a)



RE: Exercise about list of lists - micseydel - May-03-2018

That looks correct to me, but isn't how I'd solve the problem. Here's the feedback I'd give, where some of it doesn't apply once later stuff is done but I include it anyway:
1) Rather than using an index in your outer loop, you can iterate over the lists directly just like you iterate over the inner values directly in the nested loop. So you don't need range() at all.
2) You're overwriting a built-in name, "sum". On my screen, the forum renders that code as pink to indicate that it's a built-in word. Instead, I'd call it "total" or...
3) You can replace the inner loop with a call to the built-in sum function.
4) I'd not use append(), instead I would just use a list comprehension.
5) It's often best to put things like this in a well-named function.


RE: Exercise about list of lists - Otbredbaron - May-03-2018

Thanks for your answer, I think I almost got every point of your post (I'll write the function but I know how to do that so it's not an issue):

#!/usr/bin/python3

L = [[1,2,3],[5,6]] 

a = [sum(i) for i in L]
    
print (a)
Did you mean to do something like this?


RE: Exercise about list of lists - micseydel - May-03-2018

Yeah, that looks good. I'd probably call it "sub" or "collection" or "ints" or something instead of just "i" though (and L I'd probably call "lists" or something). While that's probably more Pythonic, you could also skip doing the naming -
a = list(map(sum, L))
If you only really care about producing an iterable (rather than a list) you can drop the call to list there as well. (In Python 3, map creates a generator rather than a list.)