-2
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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ihor Harmatii
  • 189
  • 3
  • 21

2 Answers2

2

list comprehension should be used only for generating a list. You can simply use sum(l).

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
2

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.

properchels
  • 260
  • 2
  • 20