Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate sum() using a list comprehension?

Tags:

python

list

Is it possible to emulate something like sum() using list comprehension ?

For example - I need to calculate the product of all elements in a list :

list = [1, 2, 3] product = [magic_here for i in list]  #product is expected to be 6 

Code that is doing the same :

def product_of(input):    result = 1    for i in input:       result *= i    return result 
like image 987
StKiller Avatar asked May 19 '13 06:05

StKiller


People also ask

How do you sum list comprehension?

To do sum, you need to have a starting list with an identity of [0], starting with [1] works for product because you are multiplying the first number by 1, hence the change to [0].

Can you use sum on a list?

sum() function in PythonSum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.


2 Answers

No; a list comprehension produces a list that is just as long as its input. You will need one of Python's other functional tools (specifically reduce() in this case) to fold the sequence into a single value.

like image 108
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 14:09

Ignacio Vazquez-Abrams


>>> from functools import reduce >>> from operator import mul >>> nums = [1, 2, 3] >>> reduce(mul, nums) 6 

Python 3 Hack

In regards to approaches such as [total := total + x for x in [1, 2, 3, 4, 5]]

This is a terrible idea. The general idea of emulate sum() using a list comprehension goes against the whole purpose of a list comprehension. You should not use a list comprehension in this case.

Python 2.5 / 2.6 Hack

In Python 2.5 / 2.6 You could use vars()['_[1]'] to refer to the list comprehension currently under construction. This is horrible and should never be used but it's the closest thing to what you mentioned in the question (using a list comp to emulate a product).

>>> nums = [1, 2, 3] >>> [n * (vars()['_[1]'] or [1])[-1] for n in nums][-1] 6 
like image 42
jamylak Avatar answered Sep 21 '22 14:09

jamylak