sum of negative integers in python

You can get the sum of negative integers in a list by using the following code in Python:

main.py
num_list = [-2, 3, 5, -6, -8, 9, -10]
sum_neg = sum(filter(lambda x: x < 0, num_list))
print("The sum of negative integers in the list is: ", sum_neg)
151 chars
4 lines

The sum() function is used to return the sum of all the elements in the list. We use the filter() function to filter out the negative numbers from the list. The lambda function is applied to each element in the list to check if it is less than zero. This will give a list of all negative numbers which will be passed to the sum function to get the sum of all the negative integers in the list.

Output:

main.py
The sum of negative integers in the list is:  -26
50 chars
2 lines

related categories

gistlibby LogSnag