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

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()
>>> # 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()
>>> # gain a little by avoiding the modulo operator
>>> Timer("sum([i for i in L if not (i & 1)])", "from __main__ import L").timeit()

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.