dissidia
dissidia

Reputation: 1581

Sum of first elements in nested lists

I am trying to get the first element in a nested list and sum up the values.

eg.

nested_list = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']]
print sum(i[0] for i in nested_list)

However, there are times in which the first element in the lists None instead

nested_list = [[1, 'a'], [None, 'b'], [3, 'c'], [4, 'd']]
new = []
for nest in nested_list:
    if not nest[0]:
        pass
    else:
        new.append(nest[0])
print sum(nest)

Wondering what is the better way that I can code this?

Upvotes: 1

Views: 1052

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

First of all, Python has no null, the equivalent of null in languages like Java, C#, JavaScript, etc. is None.

Secondly, we can use a filter in the generator expression. The most generic is probably to check with numbers:

from numbers import Number

print sum(i[0] for i in nested_list if isinstance(i[0], Number))

Number will usually make sure that we accept ints, longs, floats, complexes, etc. So we do not have to keep track of all objects in the Python world that are numerical ourselves.

Since it is also possible that the list contains empty sublists, we can also check for that:

from numbers import Number

print sum(i[0] for i in nested_list if i and isinstance(i[0], Number))

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121306

Just filter then, in this case testing for values that are not None:

sum(i[0] for i in nested_list if i[0] is not None)

A generator expression (and list, dict and set comprehensions) takes any number of nested for loops and if statements. The above is the equivalent of:

for i in nested_list:
    if i[0] is not None:
        i[0]  # used to sum()

Note how this mirrors your own code; rather than use if not ...: pass and else, I inverted the test to only allow for values you actually can sum. Just add more for loops or if statements in the same left-to-right to nest order if you need more loops with filters, or use and or or to string together multiple tests in a single if filter.

In your specific case, just testing for if i[0] would also suffice; this would filter out None and 0, but the latter value would not make a difference to the sum anyway:

sum(i[0] for i in nested_list if i[0])

You already approached this in your own if test in the loop code.

Upvotes: 3

Related Questions