Python Forum

Full Version: Exercise about list of lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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.
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?
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.)