0
I have a problem. I am finding it hard to sum up integer members of a list. I need help guys.
7 ответов
+ 6
print(sum(n for n in num if not n%2))
+ 2
Eneh Uchenna Fortune can you please add your code.
+ 2
print(sum(filtered))
+ 1
Eneh Uchenna Fortune
num = [9,5,6,8,4,2,4,2,6]
filtered = list(filter(lambda x: x % 2 == 0, num))
see what is happening here :
using lambda you are checking whether item of list num is divisible by 2 or not means it is
even or not.
so it will filter the all values which is divisible by 2
and you are converting all the evaluated values using list()
if we print the variable "filtered"
then output will be - - - >
[6, 8, 4, 2, 4, 2, 6]
if you want to sum up all the values of above list then you can simply use sum() as Rik Wittkopp said
print(sum(filtered))
which is same as --> print(sum([6, 8, 4, 2, 4, 2, 6])
output : 32
----------------
if you want to sum up all the items which is odd then you can use this expression in your lambda
x%2!=0
this will evaluate all the non even values
----------------------------
using f-strings 💪
https://code.sololearn.com/c2QBpa71UAVe/?ref=app
+ 1
You can do what David Ashton exposed, by using built-in function sum() like this:
print(sum([1, 2, 3, 4, 5, 6,])) #This is just an example, function sum takes an array of numbers as argument.
Or you can do it by using a loop and a variable as a counter:
example = [1, 2, 3, 4, 5, 6]
counter = 0
for number in example:
counter += number
I hope this help you 🙂
+ 1
Thank you everyone. You have been so helpful
0
Please I need help