Why is there a difference between two lines of code?

total = sum([float(item) for item in s.split(",")])


total = sum(float(item) for item in s.split(","))

Source: stack overflow

+4
source share
4 answers

The first uses a list to create a list of all float values.

The second uses a generator expression to create a generator that only builds each float value on demand, one time. This saves a lot of memory when the list is very large.

( , ), ( ), . :

(, , -, , , ..), . , .

, , , .


Python 2.x ; 3.x, list . ( , , 3.0-3.3, , ...)

+6

, - . sum().

In [25]: [float(a) for a in s.split(',')]
Out[25]: [1.23, 2.4, 3.123]

In [26]: (float(a) for a in s.split(','))
Out[26]: <generator object <genexpr> at 0x0698EF08>

In [27]: m = (float(a) for a in s.split(','))

In [28]: next(m)
Out[28]: 1.23

In [29]: next(m)
Out[29]: 2.4

In [30]: next(m)
Out[30]: 3.123

, , , . ( )

+5

, , , . , , , , , .

+2

.

The second calculates each element in turn and adds it to the current total amount and returns the total amount as a sum when all the elements have been exhausted. This is an understanding of the generator.
It does not create a list at all, which means that no additional time is required to allocate memory for the list and fill it. This also means that it has a higher spatial complexity since it uses only constant space (for a call float, except for a call splitthat both lines make)

+1
source

Source: https://habr.com/ru/post/1523646/


All Articles