l = [5, 7, 8, 2, 1, 4]
sum = 0
for i in l:
sum += i
print(sum)
how can I get sum of all elements but using list comprehension?
l = [5, 7, 8, 2, 1, 4]
sum = 0
for i in l:
sum += i
print(sum)
how can I get sum of all elements but using list comprehension?
list comprehension
should be used only for generating a list
. You can simply use sum(l)
.
List comprehension always produces another list so I am not sure if you can even do that. You will surely need other function to fold the sequence into a single value.