Hello,

I have the following code that using list comprehension to find even numbers in list L.

L = [1,2,3,4,5,6,7,8,9,10]
K = sum([(i) for i in L if i%2 ==0])

I wanted to know if this was the most efficient way to sum list K?

Recommended Answers

It is already efficient (1.6 microseconds on my computer)

>>> from timeit import Timer
>>> L = [1,2,3,4,5,6,7,8,9,10]
>>> # run your statement 1 million times
>>> Timer("sum([(i) for i in L if i%2 ==0])", "from __main__ import L").timeit()
1.607414960861206
>>> # removing the inner list construction …
Jump to Post

All 2 Replies

It is already efficient (1.6 microseconds on my computer)

>>> from timeit import Timer
>>> L = [1,2,3,4,5,6,7,8,9,10]
>>> # run your statement 1 million times
>>> Timer("sum([(i) for i in L if i%2 ==0])", "from __main__ import L").timeit()
1.607414960861206
>>> # removing the inner list construction is surprisingly less efficient
>>> Timer("sum(i for i in L if i%2 ==0)", "from __main__ import L").timeit()
1.9511890411376953
>>> # gain a little by avoiding the modulo operator
>>> Timer("sum([i for i in L if not (i & 1)])", "from __main__ import L").timeit()
1.4257829189300537

Thank you! I thought there might have been another way to express this, but I think this will do. Thank you again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.