jmf_zaiecp
jmf_zaiecp

Reputation: 331

Different behavior between generator expression and first constructing a list then using list-converted generator

Can these two pieces of codes generate different behavior for downstream applications? In other words, are the returning objects any different ?

 return (func(i) for i in a_list) 

and

 b_list=[] 
 for i in a_list:
     b_list.append(func(i))
 return (i for i in b_list)

PS: The second way to build generator is very questionable.

Upvotes: 0

Views: 20

Answers (1)

roeen30
roeen30

Reputation: 789

First of all, this code:

b_list=[] 
for i in a_list:
    b_list.append(func(i))
return (i for i in b_list)

Is entirely the same as this code:

return iter([func(i) for i in a_list])

The difference between these and this:

return (func(i) for i in a_list)

Is that the latter is lazy and the other two are eager - i.e the latter runs func every time its __next__() method is called and the other two run func for every item ia a_list immediately.

So, the answer depends whether func is a pure function - in this case, if it behaves the same regardless of when it is run and independently from external/global variables.

It also depends on whether the items of the list are mutable and if them or the list itself are changed by other code.

If the answers are respectively "yes" and "no", they are same save for their memory footprint.

Finally, as long we're discussing functional concepts, please consider using:

return map(func, a_list)

Instead of:

return (func(i) for i in a_list)

But only if you're using Python 3's lovely lazy map() and not Python 2's evil eager map().

Upvotes: 1

Related Questions